How to determine if variable is undefined or null in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the equality operator (==)

In JavaScript if a variable has been declared, but has not been assigned a value, is automatically assigned the value undefined. Therefore, if you try to display the value of such variable, the word "undefined" will be displayed. Whereas, the null is a special assignment value, which can be assigned to a variable as a representation of no value.

In simple words you can say a null value means no value or absence of a value, and undefined means a variable that has been declared but no yet assigned a value.

To check if a variable is undefined or null you can use the equality operator == or strict equality operator === (also called identity operator). Let's take a look at the following example:

var firstName;
var lastName = null;
// Try to get non existing DOM element
var comment = document.getElementById('comment');

console.log(firstName); // Print: undefined
console.log(lastName);  // Print: null
console.log(comment);   // Print: null

console.log(typeof firstName); // Print: undefined
console.log(typeof lastName);  // Print: object
console.log(typeof comment);   // Print: object

console.log(null == undefined)  // Print: true    
console.log(null === undefined) // Print: false

/* Since null == undefined is true, the following statements will catch both null and undefined */
if(firstName == null){
    alert('Variable "firstName" is undefined.');
if(lastName == null){
    alert('Variable "lastName" is null.');

/* Since null === undefined is false, the following statements will catch only null or undefined  */
if(typeof comment === 'undefined') {
    alert('Variable "comment" is undefined.');
} else if(comment === null){
    alert('Variable "comment" is null.');

If you try to test the null values using the typeof operator it will not work as expected, because JavaScript return "object" for typeof null instead of "null".

This is a long-standing bug in JavaScript, but since lots of codes on the web written around this behavior, and thus fixing it would create a lot more problem, so idea of fixing this issue was abandoned by the committee that design and maintains JavaScript.

Note: The undefined is not a reserved keyword in JavaScript, and thus it is possible to declare a variable with the name undefined. So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined').

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties