JavaScript · Programming

JavaScript: Difference between ‘null’ and ‘undefined’

Here’s what ECMA3 has to say about these:

  1. The undefined value is a primitive value used when a variable has not been assigned a value.
  2. The null value is a primitive value that represents the null, empty, or non-existent reference.

When you declare a variable through var and do not give it a value, it will have the value undefined.

var dodo;
dodo2;
alert(dodo); //alerts undefined
alert(typeof dodo); //alerts undefined
alert(dodo2); //alerts undefined
alert(typeof dodo2); //alerts undefined

You can declare a variable, set it to null, and the behavior is identical except that you’ll see “null” printed out versus “undefined“. This is a small difference indeed.


var gggg = null;
alert(gggg); //alerts null
alert(typeof gggg); //alerts object

Comparing undefined to null ALWAYS returns true.

if(undefined == null)
alert(‘true’);
else
alert(‘false’);

However, using the identity operator (===) returns false.

if(undefined === null)
alert(‘true’);
else
alert(‘false’);

Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.

var a = [ 'a', 'b', 'c' ];
delete a[1]; //makes this array member as undefined
for (var i = 0; i < a.length; i++)
alert(a[i]);

The result of the above script is:
0) a
1) undefined
2) c

You will also get undefined returned when reading a subscript or member that never existed.

var a = [ 'a', 'b', 'c' ];
alert(a[100]); // alerts undefined
alert(a.joker); // alerts undefined

JavaScript interpreter will never set anything to null, that’s usually what we do in our code.
While we can set variables to undefined, we prefer null because it’s not something that is ever done for us. When you’re debugging this means that anything set to null is of your own doing and not JavaScript interpreter. Beyond that, these two special values are nearly equivalent.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s