前面有提到JavaScript會在兩種情況下進行type coercion將某個值變成布林值,一種是使用邏輯運算子時,另一種則是在邏輯語境中,例如if / else陳述式裡。
舉例來說:
const balance = 0;
if(balance) {
console.log(`I still have ${balance} dollars.`);
} else {
console.log("I ran out of money!");
}
// I ran out of money!
在if / else陳述式中,會嘗試將if後面連接的()內的值轉換成布林值,而因為balance等於0,它是一個falsy value,所以布林值為false,執行的是else後面的程式碼。
const balance = 30;
if(balance) {
console.log(`I still have ${balance} dollars.`);
} else {
console.log("I ran out of money!");
}
// I still have 30 dollars.`
如果balance不為0,那麼布林值就會變成true了。
而另一種type coercion成布林值的情況是使用邏輯運算子時:
const cleanHouse = true;
const washCar = false;
console.log(cleanHouse && washCar);
// false
console.log(cleanHouse || washCar);
// true
console.log(!cleanHouse);
// false
有了布林值,我們就可以用它來做決定,例如在綠燈以及左右來車都確實停下時,我們才能過馬路:
const trafficLight = "green";
const carsStop = true;
if(trafficLight == "green" && carsStop) {
console.log("Go ahead!");
} else {
console.log("Do not cross the road!");
}
// Go ahead!
反之則否:
const trafficLight = "green";
const carsStop = false;
if(trafficLight == “green” && carsStop) {
console.log("Go ahead!");
} else {
console.log("Do not cross the road!");
}
// Do not cross the road!