0

When I try to check for a function parameter if it is defined, and use

 if (variablename === undefined) { do something };

sometimes it works as intendend, but sometimes(mainly very early on, when some scripts are possibly still loading) I get a javascript error, that states that

variablename is undefined

If I use

if (typeof variablename == 'undefined') 

it works everytime.

Is the === undefined has some prerequisites, or what could be the problem?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Adam Baranyai
  • 3,635
  • 3
  • 29
  • 68
  • 1
    `console.log(variablename)` will result in *variablename is undefined*. However, `var variablename = undefined; console.log(variablename);` will just print undefined – CodingIntrigue Jun 17 '15 at 12:27
  • if a name is not defined it will throw an error, if the value is undefined it works. – Hacketo Jun 17 '15 at 12:27
  • You are doing something wrong if you don't know whether your variables are declared or not. – Oriol Jun 17 '15 at 12:34

1 Answers1

1

The first thing that variablename === undefined does is to read the value of variablename.

It could be a variable which has the value undefined (which will work fine) or it could be a variable that isn't defined at all … which will throw a reference error.

Using typeof won't throw a reference error.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335