Null vs Undefined vs 0

·

2 min read

null

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

null == undefined // true
null === undefined // false
null == 0 // false
null == true // false
null == false // false

let v1 = null
if (v1) console.log(`v1 is truthy`)
else console.log(`v1 is falsy`) // v1 is falsy

undefined

The global undefined property represents the primitive value undefined (automatically assigned to variables that have just been declared, or to formal arguments for which there are no actual arguments.). It is one of JavaScript's primitive types.

undefined == true // false
undefined == false // false
undefined == 0 // false

let a
if (a === undefined) console.log(`a is declared, but its value is undefined`) // a is declared, but its value is undefined

What else is undefined?

An empty index in a string

let str1 = ''
console.log(str1[0]) // undefined

let str2 = 'a'
console.log(str2[1]) // undefined

An empty index in an array

let arr1 = []
console.log(arr1[0]) // undefined

let arr2 = ['a']
console.log(arr2[1]) // undefined

0 (Zero)

0 == false // true
0 === false // false
0 == undefined //false
0 == true // false

if (0) console.log(`0 is truthy`)
else console.log(`0 is falsy`) // 0 is falsy

What else equals to 0?

An empty string == 0

let str1 = ''
console.log(str1 == 0) //true
console.log(str1 === 0) // false

An empty array == 0

let arr1 = []
console.log(arr1 == 0) //true
console.log(arr1 === 0) // false