User Name:

User Email:

This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2018 - First Crazy Developer (Abhishek Kumar)

crazydeveloper JavaScript - null and undefined

Both null and undefined can be regarded as a special value that indicates "no value".

The null is a language keyword (in fact, it is a primitive ) which is used to indicate the expected lack of value. On the other hand, undefined is a predefined global variable that has a deeper meaning and is used to indicate an error-like, unexpected lack of value.

When your function has no return value, it returns undefined. If you declare a variable and don't initialize it, it returns the undefined value. If you query a non-existent array element or object property, again an undefined is returned. Here is an example.

  • var book;
  • alert(book); // => undefined
  • alert(typeof book); // => undefined

If you want to indicate the 'lack of value' in your code, you typically use null rather than undefined.

  • var book = null;
  • alert(book); // => null
  • alert(typeof book); // => object (although null is not a true object)

Both null and undefined qualify as false when a Boolean value is required. They don't have any properties. If you attempt to access a property on them, an exception will be raised.

Null is a primitive and this is to be a bug in JavaScript from begining. The ECMAScript specifications all the way back to the very first one released in mid 1997 have stated in no uncertain terms that null is a primitive value and not an object value.

For reference (check the 'null' heading):

It is considered good practice to leave the use of undefined to JavaScript. In other words, let JavaScript determine if something is undefined, rather than you setting variables or properties to undefined. If your app requires that a variable or property value is unknown, give it a value of null and not undefined.

It is interesting to note that undefined is implemented as a global variable named 'undefined'. Its value is undefined. Since it is a global variable, there is nothing that prevents a malicious coder from re-assigning the value of undefined to something else, like so:

  • // hacker's code
  • undefined = true;

crazydeveloper Home Page 09 June 2015

Become a Fan