JavaScript 核心篇 學習筆記: Chap.25 — Truthy and Falsy

Truthy(真值)與Falsy(假值)與隱性轉型的概念是不同的

Yi-Ning
3 min readDec 15, 2019

以下是MDN對Truthy的定義

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, 0n, "", null, undefined, and NaN).

我們來看一些範例程式碼:

if (1) {
console.log(‘執行 If’);
} else {
console.log(‘執行 Else’);
}

無論我們將if裡面換成0以外的任何數字,任何非空的字串,true,甚至是空陣列 [],空物件{},都會執行 If,因為這些值都是truthy。

可以透過以下這個表,查詢if()裡面放入各種不同類型的值時的結果:

相反的,if裡面若是falsy值,則會印出“執行 Else”。

if (0) {
console.log(‘執行 If’);
} else {
console.log(‘執行 Else’);
}

值得注意的是,如果我們是以new關鍵字建構一個Number實例,其值為0時,因為我們建構出來的是一個object,object就算為空也是truthy,new Number(0)想必也會是truthy。

if (new Number(0)) {
console.log(‘執行 If’);
} else {
console.log(‘執行 Else’);
}

同理,new Boolean(false)也是truthy。

--

--