Anita
Anita

Reputation: 2400

JavaScript variable definition confusion

I have 2 javascript code. Bothe of them check if varable equal to null or type of variable is undefined. But in one condition I get error and in other I don't get any error.

Code 1:

if (NS1 === null || typeof (NS1) === 'undefined') {
    ...  }

Code 2:

 if (window.NS1 === null || typeof (window.NS1) === 'undefined') {
  ...   }

For code 1 I get error

NS1 is not defined

while for code 2 I don't get any error. I don't understand what might be the reason as i have not defined NS1 or window.NS1 . So I should get error in both the condition.

Upvotes: 0

Views: 67

Answers (2)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

It's because null === undefined // --> false

NS1 === null refers to variable NS1 which is not defined, so it throws exception.

But window.NS1 === null will evaluate as false, because window.NS1 is undefined. And undefined is not equal to null

NS1 as undeclared variable --> exception
window.NS1 as undeclared property --> undefined

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816552

So I should get error in both the condition.

Trying to access1 an undeclared variable results in a reference error. However, trying to access a non-existing property, like you do in the second example, will simply return undefined, not throw an error:

> console.log({}.foo);
undefined

That's just how JavaScript works.


1: One could argue that you are also accessing the variable when you do typeof NS1. While that's true, typeof is special. It will return "undefined" even if the variable is not declared.

Upvotes: 6

Related Questions