Javascript Null Vs Undefined

Ignacio Ojanguren
2 min readNov 11, 2021

--

Let’s go first over the definition of null and undefined:

  • Undefined: is a primitive value, and this value is assigned to variables that have just been declared during Hoisting.
  • Null: is a primitive value, and represents the absence of any value.

In these definitions we can see some similarities between undefined, and null, but they have different meanings, and uses.

Lets go over the similarities:

  • Both are primitive values.
  • Both are falsy.
!!undefined // will return false
!!null // will return false
null == undefined // will return true because both are falsy

Let’s go over the differences:

  • The type of undefined is undefined vs the type of null is an object.
console.log(typeof undefined) // will return 'undefined'
console.log(typeof null) // will return 'object'
  • Undefined is used to express a variable has never been assigned any value vs Null explicitly represents the absence of any value.
  • When you strictly compare undefined, and null they are not the same.
console.log(null === undefined) // will return false

When do you want to use null vs undefined?

  • When you are writing a piece of code, and you want a function to return an empty value, you MUST use the value of Null instead of Undefined.
  • A way to remember this is by thinking Undefined should be used by JavaScript, and Null should be used by the developer.

--

--

Ignacio Ojanguren

Over 3 years of experience as a Software Engineer at Privy, recently acquired by Attentive Mobile. I am Learning, and I hope I can share what I learn with you.