result = value1 || value2 || value3;
alert( null || 0 || 1 ); // 1 (the first truthy value)
alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)
假設有一串變數,其中有些是空的有些有存資料,可以用 or 判斷。
let currentUser = null;
let defaultUser = "John";
let name = currentUser || defaultUser || "unnamed";
alert( name ); // selects "John" – the first truthy value
短路檢測:可以用來寫精簡的 if statement 。
let x;
true || (x = 1);
alert(x); // undefined, because (x = 1) not evaluated
let x;
false || (x = 1);
alert(x); // 1
&& (AND)
如果參數皆為真,返回 true,若有錯誤返回 false。
result = a && b;
alert( true && true ); // true
alert( false && true ); // false
alert( true && false ); // false
alert( false && false ); // false
if (1 && 0) { // evaluated as true && false
alert( "won't work, because the result is falsy" );
}
AND finds the first falsy value
and 由左至右尋找第一個錯誤值,若皆無錯誤,返回最後一個值。
result = value1 && value2 && value3;
alert( null && 5 ); // null
alert( 1 && 2 && null && 3 ); // null
alert( 1 && 2 && 3 ); // 3, the last one
短路檢測:可以用來寫精簡的 if statement 。
let x = 1;
(x > 0) && alert( 'Greater than zero!' );
// same
let x = 1;
if (x > 0) {
alert( 'Greater than zero!' );
}