The undefined
value is used by JavaScript in two slightly different ways.
The first way it's used is to indicate that a declared variable (var foo
) has no assigned value. The second way it's used is to indicate that an object property you're trying to access is not defined (it has not even been named), and is not found in the prototype chain.
In the following sample, I examine both usages of undefined
by JavaScript.
Sample: sample62.html
<!DOCTYPE html><html lang="en"><body><script> var initializedVariable; // Declare variable. console.log(initializedVariable); // Logs undefined. console.log(typeof initializedVariable); // Confirm that JavaScript returns undefined. var foo = {}; console.log(foo.bar); // Logs undefined, no bar property in foo object. console.log(typeof foo.bar); // Confirm that JavaScript returns undefined. </script></body></html>
It is considered good practice to allow JavaScript alone to use undefined
. You should never find yourself setting a value to undefined
, as in foo = undefined
. Instead, null
should be used if you are specifying that a property or variable value is not available.
The undefined
Variable
Unlike previous versions, JavaScript ECMA-262 Edition 3 (and later) has a global variable called undefined
declared in the global scope. Because the variable is declared and not assigned a value, the undefined variable is set to undefined
.
Sample: sample63.html
<!DOCTYPE html><html lang="en"><body><script> // Confirm that undefined is a property of the global scope. console.log(undefined in this); // Logs true. </script></body></html>
Conclusion
Having a good understanding of the undefined
value is critical while working with JavaScript.
Comments