Press "Enter" to skip to content

difference between null and undefined in JavaScript

How do we differentiate between ‘null’ and ‘undefined’, in JavaScript? what do ‘undefined’ and ‘null’ have in common? Read on to understand.
Both ‘undefined’ and ‘null’ are JavaScript data types. Other data types are ‘String’, ‘Number’, ‘Boolean’, ‘Array’ and ‘Object’. Converting both ‘undefined’ and ‘null’ into a Boolean will return ‘false’.

Boolean(null); // returns false
Boolean(undefined); // returns false

undefined

A variable declared, but no value assigned to it is ‘undefined’. In other words, the value of a variable with no value is ‘undefined’. The typeof(undefined) is ‘undefined’. ‘undefined’ is a constant.

var foo;
foo; // is undefined
typeof(foo); // is undefined

null

‘null’ is an assignment value. ‘null’ can be used to set a variable as ‘no value’. So using ‘null’ we can empty a variable value. The typeof(null) is an Object.

var bar = null;
bar; // is null;
typeof(bar); // is Object