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?

3
  • 1
    console.log(variablename) will result in variablename is undefined. However, var variablename = undefined; console.log(variablename); will just print undefined Commented Jun 17, 2015 at 12:27
  • if a name is not defined it will throw an error, if the value is undefined it works. Commented Jun 17, 2015 at 12:27
  • You are doing something wrong if you don't know whether your variables are declared or not. Commented Jun 17, 2015 at 12:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.