Categories
JavaScript Tutorials

Undefined and null

You get the undefined value when you try to use a variable that doesn’t exist, or one that hasn’t When you declare a variable without been assigned a value. When you declare a variable without initializing it, JavaScript automatically initializes it to the value undefined. If you try using a non-existing variable, you’ll get an error message:

console.log(foo)
//foo is not defined

If you use the typeof operator on a non-existing variable, you get the string “undefined”.

console.log(typeof foo)
//"undefined"

If you declare a variable without giving it a value, you won’t get an error when you use that variable. But the typeof still returns “undefined”.

var somevar;
console.log(typeof somevar)
//"undefined"

The null value, on the other hand, is not assigned by JavaScript behind the scenes; it can only be assigned by your code.

var somevar = null
console.log(somevar)
//null

var somevar = null
console.log(typeof somevar)
//"object"

Although the difference between null and undefined is small, it may be important at times. For example, if you attempt an arithmetic operation, you can get different results:

var i = 1 + undefined; 
console.log(i);
//NaN

var i = 1 + null; 
console.log(i);
//1

This is because of the different ways null and undefined are converted to the other primitive types. Below are examples that show the possible conversions.

Conversion to a number:

console.log(1*undefined)
//NaN

console.log(1*null)
//0