What’s the difference between a variable that is: null, undefined, or undeclared?

Short Answer

  • undeclared: variable not declared with the var statement

  • undefined: variable declared with the var statement but no value assigned

  • null: variable declared and with null value

1
2
3
a = 0;         // undeclared
var b;         // undefined
var c = null;  // null

Let’s talk about it

In ECMAScript we have five data types that are primitives:

  • Boolean

  • Number

  • String

  • Undefined

  • Null

and Object.

These two latter points (and undeclared that is not a data type but it is just when you use a variable without declaring with the var statenebt) will be the subject of this article.

We can check if a variable is undefined or null, but as usual in javascript we should keep our eyes skinned.

1
2
3
4
5
6
typeof(a) === undefined;   // true
a === undefined;           // ReferenceError: a is not defined

var b;
typeof(b) === undefined;   // true
b === undefined;           // true

The variable a is undeclared, thus, when we try to check it’s value we got a ReferenceError. Otherwise, when we access the type of a we got undefined. The type of an undeclared variable is undefined.

What about null ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var a = null;
var b;

typeof(a)           // object

a === null;         // true
a === b;            // false
a === undefined     // false
b === undefined     // true

a == undefined      // true
a == b;             // true
b == null           // true

null == undefined   // true
null === undefined  // false

Javascript is Dynamic typed, thus, the type checking is performed at run time.

If a var has null value then its type at run time is object (Even if null is a primitive)

The strict comparison (===) between null and undefined is false (as it really is).

Whereas the most used comparison operator (==) gives true as result because it converts the operands to the same Type before making the comparison.

To read about the difference between === and == read my previous post.

Resources: