JavaScript Basics: Null vs. Undefined!

  • undefined — the default primitive value of declared variables that have not yet been assigned a value (either in the code or during the creation phase of the execution context)
  • null — an assigned primitive value (by someone) to indicate an empty value // never a default value

In other words, undefined simply means that the value of the variable hasn’t been defined yet (and we don’t know if it will ever be).

There are at least 8 ways to get undefined:

  1. A declared variable without assigning any value to it.
  2. Default return of functions that lack return statements.
  3. Return statements that do not explicitly return anything.
  4. Result of looking up non-existent properties in an object.
  5. Function parameters that have not passed.
  6. Any variable that has been intentionally set as undefined.
  7. Using the void operator.
  8. The value of the global variable undefined (it is a property of the global object).

On the other hand, null means that the value is empty or lacks a value that has been intentionally set by a programmer. The machine does not set variables to null for you. It is a purposed primitive.

Checking Equality!

typeof null;          // "object" (not "null" for legacy reasons)
typeof undefined; // "undefined"
null === undefined; // false
null == undefined; // true
null === null; // true
null == null; // true
!null; // true
isNaN(1 + null) // false
isNaN(1 + undefined) // true

Read more:

  • MDN docs — null
  • MDN docs — undefined
Like what you read? Give Dan Park a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.