Last Updated: February 25, 2016
·
1.318K
· andrefarzat

Avoid using typeof to test undefined

Since ECMAScript 5, the keyword undefined is non-writable. That means it is no more necessary to check the type of the variable once it is better and simpler just comparing it to undefined.

This will not cause any problems if you use 'use strict' once it forces you to declare the variables in the scope.

Picture

Sources:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined

6 Responses
Add your response

unless you really need to support old browsers, ie. IE8

over 1 year ago ·

what happens if undefined is redefined in a script without strict mode, couldn't that affect undefined on my scrict-mode block?

over 1 year ago ·

@benjamine although no error is shown, it isn't redefined. The same happens if you try to redefine window.document, for example.
For ie8, you're right, it is possible to redefine undefined, however, if your code runs in strict mode in modern browsers, it won't be a problem in ie8.

over 1 year ago ·

well if you want to support ie8 (please don't!! :)), if your code works fine on modern browsers with strict mode, you can still have errors on ie8, even worse, you can get errors that only show up on ie8, so testing gets harder.
Of course though if someone redefines undefined should go to prison for the rest of his/er life :)

over 1 year ago ·

@benjamine strongly agree with you! haha. That's why I am really careful when I select a jQuery plugin. Usually I avoid selecting one which doesn't have the 'use strict' declaration.

over 1 year ago ·

It is still necessary to use typeof to check whether a variable actually is defined, though.

over 1 year ago ·