Elaine's Blog 朝著 senior 前進的工程師

JavaScript null、undefined 與 undeclared

2019-09-09

  • undefined 是一種型態,代表此處應有,但是現在還沒有

    • 宣告了,但是還沒有賦值

      var a = undefined;
      console.log(a); // undefined
      console.log(typeof a); // undefined
      
      var b;
      console.log(b); // undefined
      
    • 物件沒有該屬性

      var person = {
        name: "elaine",
      };
      console.log(person.age); // undefined
      
    • 函式沒有回傳值

      function sayHi() {}
      console.log(sayHi()); // undefined
      
    • 呼叫函式,沒有帶入參數

      function sayHi(name) {
        console.log(name); // undefined
      }
      sayHi();
      
  • undeclared 代表未宣告

    • 在嚴格模式,會噴錯 Uncaught ReferenceError: a is not defined

      // 嚴格模式,Uncaught ReferenceError: a is not defined
      "use strict";
      a = 10;
      console.log(a);
      
    • 在非嚴格模式,該變數會變成全域變數

      // 非嚴格模式,變成全域變數
      a = 10;
      console.log(a);
      
      console.log(a); // 未宣告直接取值,Uncaught ReferenceError: a is not defined
      
  • null 是一種型態,代表空值

    • 物件原型鍊的終點
    var a = null;
    console.log(a); // null
    console.log(typeof a); // object
    

Similar Posts

Content