1. Technology

Null and Undefined

By

Both null and undefined in JavaScript can behave in ways that you might not expect.

Null sometimes behaves as an object and sometimes not. If you use typeof to test for what null is then JavaScript will identify null as an object. On the other hand, null is the only object in JavaScript that is not an instanceof the Object object. Fortunately neither of these tests would be very commonly applied within any script and so the difference in the results. In just about all of the cases where you would use null in your JavaScript code you would not care whether JavaScript treats it as an object of not.


alert(typeof null); // object
allert(null instanceOf Object) // false

Undefined is not a reserved word. What this means is that you can actually define your own variable called undefined and give it whatever value that you want. If you do that then undefined will behave in the way you'd expect the variable that you created to behave and you may get entirely different results to what you would expect if you didn't redefine undefined.

Also, even though null and undefined are supposed to mean different things - with one meaning that the variable doesn't exist and the other meaning that the variable exists but doesn't have a value, null and undefined are considered to be equal when you compare them in JavaScript. This occurs because simply referencing a variable name in a statement in order to test if that variable exists or not will create the variable.


alert(anything == undefined);
alert(anything == null);

Both of these alerts will display "true" provided that the "anything" variable has not had a value assigned to it. In the case of the test against null the variable is actually created by the statement itself and so strictly speaking the variable is undefined rather than null however JavaScript teats null and undefined as being equivalent in this instance.

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Null and Undefined

©2014 About.com. All rights reserved.