You may wonder whats the difference between null
and undefined
in javascript. Some even said they’re interchangeable. Is it true? Let’s see..
null == undefined //true
null === undefined //false
null ? 1 : 2 //2
undefined ? 1 : 2 //2
1 + null //1, null becomes 0
1 + undefined //NaN
undefined + null //NaN
undefined + undefined //NaN
null + null //0
function add(a = 1, b) {
console.log(a + b)
}
add(null, 2) //2, null becomes 0
add(undefined, 2) //3, default value applied
add(2) //NaN, as the 2nd argument is undefined
1 + null //1, null becomes 0
1 + undefined //NaN
undefined + null //NaN
undefined + undefined //NaN
null + null //0
function add(a = 1, b) {
console.log(a + b)
}
add(null, 2) //2, null becomes 0
add(undefined, 2) //3, default value applied
add(2) //NaN, as the 2nd argument is undefined
though both will be treated as false
during boolean evaluation, null
will be evaluated as 0 in arithmetic operation. This subtle difference may cause unexpected bugs, watch out~