Fraser Hamilton

JavaScript undefined vs null

July 09, 2020

In JavaScript both undefined and null primitive types.

let foo

console.log(foo)

// undefined

A variable is undefined when it has been declared but not assigned a value.

let bar = null

console.log(bar)

// null

For a variable to be null it must be directly assigned the value.

You can check for equality for both primitives using === like so:

let foo
let bar = null

console.log(foo === undefined)

//true

console.log(bar === null)

//true

And as they are both falsy values they will be false when coalesced to a boolean.

let foo
if (!foo) {
  console.log('foo is False')
}

// Foo is False

let bar = null
if (!bar) {
  console.log('bar is False')
}

// bar is False

However there’s some slightly unexpected behaviour when we use the typeof operator.

let foo
typeof foo

// undefined

let bar = null
typeof bar

// object

Despite being a primitive type null evaluates to an object.


Written by Fraser Hamilton a full stack developer based out of Edinburgh, Scotland.

© 2020, Fraser Hamilton