undefined in JavaScript
JavaScript is very flexible that sometimes not knowing to use it safely
would end up causing pitfalls. This post explains the traps of undefined
in JavaScript and ways to overcome them.
undefined is one of JavaScript’s six primitive data types.
|
|
undefined is implemented in Javascript as a property of the global object with value undefined. It is the the default value for all initialized variables with no assignment and functions without any return value.
|
|
The interesting thing about undefined is that it is mutable in versions of JavaScript below EcmaScript 5. The language allows different values of different data types to be set on undefined which might cause some worse programming behaviours. Some examples of assigning values to undefined are as below.
|
|
One of the most prominant ways to avoid the above effect of assigning unwanted values to undefined and to make sure that undefined has it default intented value is to use the below pattern. It could be seen in jQuery source and a lot of plugins as well.
|
|
Another way to make sure that undefined is set properly is to use the uncommon JavaScript language feature void. It is a function which when used with an expression, executes the expression and returns undefined.
|
|
But the best of all elegant solution would be to use strict mode. Strict mode in EcmaScript 5 changes all silently failing errors into throwable errors in JavaScript.
|
|
Comments