Null, Undefined and Delete

by jeremyjones on March 19, 2011

  • Share
  • CevherShare
  • Share

Unlike most other programming languages, you can use both undefined and null values in JavaScript. This can be confusing for someone who comes to JavaScript from another programming language. When an object is undefined, it means that it has still to be declared or has been declared and not given a value. Null is a special value that means an object has no value, and JavaScript deals with null as an object. These two values are different types, and are considered equal by the equality, ==, operator but not the identity, ===, operator.

<br />
alert(typeof i);  // Returns undefined<br />
>var x = null;<br />
alert(typeof x);	// Returns object<br />
>var j;<br />
alert(typeof j);  // Also Returns undefined<br />

The JavaScript delete operator will remove a property definition. This can be useful if you wish to apply it to object properties and array members. It is possible to delete any variable that you declare implicitly, but you cannot delete variables that you declare with var.

<br />

var obj = {<br />
  val: 'Some string'<br />
}<br />
alert(obj.val); // displays 'Some string'</p>
<p>delete obj.val;<br />
alert(obj.val); // displays 'undefined'<br />

There are several ways to check whether a value is null or undefined. These examples all show ways to check the status of a variable:

<br />
If (myval == null)	// Checks for null with casting<br />
If (myval === null)	// Checks for null without casting<br />
If (typeof myval != ‘undefined’)	// Any scope<br />
If (window[‘varname’] != undefined) // Global scope<br />
If (myval != undefined)	// Myval exists but don’t know the value<br />

It is important to know the difference between these different values and use them properly. Otherwise, you could unintentionally introduce errors into your code.

Leave a Comment

Previous post:

Next post: