null vs undefined

Cindy Zheng
2 min readSep 14, 2020

Before we get into null and undefined, we should learn two concepts: javascript primitive values and falsy values. They will help us understand null and undefined, since both null and undefined are JavaScript’s primitive values and are treated as falsy (not false) for boolean operations ( “AND”, “OR” and “NOT”).

primitive values

JavaScript sets a value to one of six primitive data types:

  • Undefined (a variable with no defined value)
  • Null (a single null value)
  • Boolean (true or false)
  • Number (this includes Infinity and NaN – not a number!)
  • String (textual data)
  • Symbol (a unique and immutable primitive new to ES6/2015)

Falsy values

  • false
  • 0 (zero)
  • '' or "" (empty string)
  • null
  • undefined
  • NaN

null

null means “no value”.

“The value null represents the intentional absence of any object value.”

let a = null
console.log(a)//null
null == false //falseconsole.log(!null) // true

undefined

A variable that has been declared but no value assigned or an object’s property does not exist will return undefined.

let b
console.log(b) //undefined
let Amy = {gender: "female"}
console.log(Amy.age) // undefined

A function returns undefined if a value was not returned.

function test1(){
let a = 1
console.log(a) //1
}
console.log(test1())//undefined
function test2(){
let a = 1
console.log(a) //1
return a
}
console.log(test2())//1

Last, null and undefined are both falsy, they are loose equal to each other:

null == undefined //true
null !== undefined //true

resources:

--

--