1

I want to check if a variable is defined before using it, so I wrote something like this

if(!variable){
    return null;
}

But it throws an error

ReferenceError: variable is not defined

If I do it like this

if(typeof variable === 'undefined'){
    return null;
}

It works as expected.

What is the difference between the approaches and why it didn't return null in the first example but instead it died with the error ?

Stevik
  • 1,092
  • 2
  • 16
  • 37
  • 3
    possible duplicate of [What is the difference in Javascript between 'undefined' and 'not defined'?](http://stackoverflow.com/questions/833661/what-is-the-difference-in-javascript-between-undefined-and-not-defined) – Artyom Neustroev Jul 28 '15 at 10:41
  • 1
    You are using variable without defining it. The value of variable is unknown. Javascript not allow us to do this. – Kiran Shinde Jul 28 '15 at 10:41

1 Answers1

2

When !variable is evaluated it tries to get the value of the variable which as per spec will throw an ReferenceError.

But calling typeof will not initially try to get the value of the variable, instead it will check whether the passed expression is a reference, if so then it will check if it is resolvable if nor undefined is returned.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531