What is the difference between null and undefined in JavaScript?

前端 未结 30 3272
夕颜
夕颜 2020-11-21 23:06

I want to know what the difference is between null and undefined in JavaScript.

30条回答
  •  借酒劲吻你
    2020-11-21 23:36

    In addition to a different meaning there are other differences:

    1. Object destructuring works differently for these two values:
      const { a = "default" } = { a: undefined }; // a is "default"
      const { b = "default" } = { b: null };      // b is null
      
    2. JSON.stringify() keeps null but omits undefined
      const json = JSON.stringify({ undefinedValue: undefined, nullValue: null });
      console.log(json); // prints {"nullValue":null}
      
    3. typeof operator
      console.log(typeof undefined); // "undefined"
      console.log(typeof null);      // "object" instead of "null"
      

提交回复
热议问题