What is the difference between null and undefined in js?

The difference between null and undefined:

1. The data types are different

Use typeof to judge, the data type of null is object, and the data type of undefined is undefined

typeof(null) //object  typeof(undefined) //undefined

2. The values ​​of null and undefined are equal, but when the two are compared for equality, the two are not equal. (because their data types are different)

null==undefined //true  null===undefined //false
//理解:=是赋值 ==是值相等  ===值和数据类型都相等

3. The values ​​converted into numbers are different

Number(null) //0         Number(null+2) //2
Number(undefined) //NaN  Number(undefined+2) //NaN

4. Null means "empty", which means a null pointer; undefined variable has not been declared or has been declared but has not been assigned (uninitialized)

let a;
console.log(a); // undefined
let b=null;
console.log(b) // null

Guess you like

Origin blog.csdn.net/weixin_45308405/article/details/127839485
Recommended