null vs undefined
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
andNaN
– 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)//nullnull == 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) //undefinedlet 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: