1

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.

Anita
  • 2,352
  • 2
  • 19
  • 30
  • 1
    `NS1 === null` --- you're trying to retrieve a value of the variable that does not exist. – zerkms Aug 28 '15 at 05:35
  • `typeof` is not function. Use like `typeof window.NS1` – Manwal Aug 28 '15 at 05:38
  • 2
    If you move the `typeof` check to the left-hand-side of the `||`, you won't get any errors at all due to short-circuit evaluation ~ `if (typeof NS1 === 'undefined' || NS1 === null)` – Phil Aug 28 '15 at 05:39
  • Note that this is a special case, only global variables can be accessed as properties of some object (the global/window object). Variables within function's can't be accessed as properties, so for them you must use *typeof* if uncertain. – RobG Aug 28 '15 at 05:53

2 Answers2

6

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

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

Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69