What is the difference between null and undefined?

null is a keyword in js, indicating a null value; null can be regarded as a special value of object. If the object value is empty, it means that the object is not a valid object;

undefined is not a keyword in js, it is a global variable and a property of Global;

Undefined will be returned in the following situations:

  • If the variable has been declared but not assigned a value, it is equal to undefined;
  • When the function is called, no actual parameter is provided, and the parameter is equal to undefined;
function fun1( a ){
    console.log( a )
}

fun1();  //undefined  (形参只是声明了,未传入实参=未赋值) 
  • When using an object property, but the property is not assigned a value or does not exist, the property value is undefined;
  • When the function does not return a value, it returns undefined by default;
var a = function(){};

console.log(a);   //undefined

1. Similarity

In JavaScript, null and undefined represent "none", and they are both primitive type values ​​and are stored on the stack ;

for example:

Assign variable a to null or undefined, there is almost no difference between the two writing methods;

var a = null;
var a = undefined;

unll and undefined will be automatically converted to false in the if statement;

if(!undefined)
    console.log(" undefined is false ")

        //undefined is false


if(!null)
    console.log(" null is false ")
        
        //null is false




console.log(undefined == null); // true  (作比较时,unll与undefined自动转换为false)

//PS  : 三等与两等不同;

console.log(undefined === null); // false  (unll为0与undefined为false,三等为false)

2. Difference

1. Different types;

2. It is different when converting the value;

type:

      console.log( typeOf undefined );    // undefined

      console.log( typeOf null );    // object

Conversion value:

      console.log(  Number(undefined) );    // NaN

      console.log(  Number(undefined+10) );    // NaN

      console.log(  Number(null) );    // 0

      console.log(  Number(null+10) );    // 10

3. Use

null When a larger object is used up and its memory needs to be released, the object can be set to null.

      var arr = [ 111,222,333 ];

      arr = null; //Release the reference to the array;

Guess you like

Origin blog.csdn.net/weixin_42220533/article/details/122348214