Javascript
null vs undefined vs undeclared

null vs undefined vs undeclared

Null

  • variable with null has been explicitly assigned to a value which represents no value
  • check if a variable is null by using === operator

Undefined

  • variable that is undefined has been declared but not assigned a value
  • check if a variable is undefined by using typeof operator or === operator

Undeclared

  • variable is undeclared if it has not been declared using var, let, or const keywords, these variables will be declared globally but will throw ReferenceError in strict mode
  • check if a variable is undeclared by using try and catch block

Never leave variables undeclared or unassigned Never use == operator to check for null or undefined

console.log(null == undefined); // true