close

undefined

  • undefined 是變數沒有被宣告,或者是已經宣告了,但是沒有賦值,Javascript 將未賦值的變數的預設值設為 undefined。

 

let _thisIsUndefined;
const doNothing = () => {};
const someObj = {
  a : "ay",
  b : "bee",
  c : "si"
};
console.log(_thisIsUndefined); //logs undefined
console.log(doNothing()); //logs undefined
console.log(someObj["d"]); //logs undefined

 

  • 不是一個有效的 JSON。
  • 判斷一個變數是否為 undefined。

 

typeof variable === "undefined"

 

 

null

  • null 意思是「沒有值」的值。
  • 是一個有效的 JSON。
  • 作為函式的參數,該函式的參數不是對象。

 

Object.getPrototypeOf(Object.prototype) // null

console.log(document.querySelector('h5')) // 做 DOM 元素操作時,若要獲取的 DOM 元素不存在,會回傳 null。

 

  • null 的類型(typeof)是一個 object。(原因是 javaScript 的 bug)
  • 判斷一個變數是否為 null。

 

variable === null

 

相似處

undefined 和 null 相似處:

  • 都没有屬性和方法,也不能額外添加屬性方法。
  • 皆為 Falsy Value (Boolean 判斷時為 false)

 

console.log(!!null); //logs false
console.log(!!undefined); //logs false
console.log(Boolean(null)); //logs false
console.log(Boolean(undefined)); //logs false

 

  • 皆為原始型別 (Primitive Type)

 

null == undefined // true 因為都是 false
null === undefined // false 因為 typeof(null) 是 Object, typeof(undefined) 是 undefined

 

Ref:
https://www.jstips.co/zh_tw/javascript/differences-between-undefined-and-null/

https://medium.com/@snh90100/javascript%E4%B8%ADundefined%E5%92%8Cnull%E7%9A%84%E5%B7%AE%E5%88%A5-1f48e9be5e02

https://dev.to/macmacky/70-javascript-interview-questions-5gfi#1-whats-the-difference-between-undefined-and-null

https://2ality.com/2013/10/typeof-null.html?ck_subscriber_id=952607343

arrow
arrow
    文章標籤
    JavaScript 前端 Javascript
    全站熱搜

    瑞哈 發表在 痞客邦 留言(0) 人氣()