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.
Sources:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined
Written by André Farzat
Related protips
6 Responses
unless you really need to support old browsers, ie. IE8
what happens if undefined is redefined in a script without strict mode, couldn't that affect undefined on my scrict-mode block?
@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.
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 :)
@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.
It is still necessary to use typeof to check whether a variable actually is defined, though.