CodePark/ questions / Types & coercion
START PRACTICINGPRACTICE
Frontend question · JavaScript › Types & coercion

What is the difference between null and undefined?

undefined means no value was given, and it is JavaScript's default. null means "empty", and a developer sets it on purpose.

JavaScript gives you undefined automatically in these cases:

  • a variable that was declared but not given a value
  • an object property that does not exist
  • a function argument that the caller did not pass
  • the result of a function with no return

You write null yourself to say "there is no object here", for example let selectedUser = null before the user picks anyone.

They are different types. typeof undefined is 'undefined'. typeof null is 'object', because of an old bug that was never fixed.

They are loosely equal: null == undefined is true. They are not strictly equal: null === undefined is false. So x == null is a common short way to check for both at once.

Some features treat them the same and some do not:

  • ?? and ?. treat both as missing.
  • Default parameters are used only for undefined, not for null.
  • JSON.stringify drops properties whose value is undefined, but keeps null.
  • undefined is JavaScript's default when nothing was assigned or something is missing.
  • null is set on purpose by a developer to mean "empty".
  • typeof null === 'object' is an old bug that was kept.
  • null == undefined is true, but null === undefined is false.
  • Default parameters apply only for undefined. JSON.stringify drops undefined but keeps null.