null vs undefined

Similarities

  • Both are primitives
  • Both are falsy:
    • 1
      Boolean(undefined) //-> false
      2
      Boolean(null) //-> false
      Copied!

Differences

  • undefined means that a variable has not been declared, or it has been declared but has not yet been assigned a value.
  • null is an assignment value that means “no value”. Javascript itself never sets a value to null
  • Difference in typeof:
    • 1
      typeof null; //-> "object"
      2
      typeof undefined; //-> "undefined"
      Copied!
  • undefined is not a valid JSON while null is.

Tips

  • Check if a variable is null:
1
variable === null;
Copied!
  • Check if a variable is undefined:
1
typeof variable === 'undefined';
2
3
// ⬇️ or this, but will throw ReferenceError if variable wasn't defined
4
variable === undefined;
Copied!
  • Comparison (Equality returns true and identity returns false) :
1
undefined == null; //-> true
2
3
undefined === null; //-> false
Copied!