> For the complete documentation index, see [llms.txt](https://mistborn.gitbook.io/til-coding/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mistborn.gitbook.io/til-coding/javascript/logical-operators.md).

# Logical operators

## || (OR)

任何一個參數為真，返回 `true`，皆為錯誤，返回 `false`，非布林值的參數會轉為布林值，大多時候用在 if statement 檢測任一判斷式是否為真。

```javascript
alert( true || true );   // true
alert( false || true );  // true
alert( true || false );  // true
alert( false || false ); // false

if (1 || 0) { // works just like if( true || false )
  alert( 'truthy!' );
}

let hour = 12;
let isWeekend = true;

if (hour < 10 || hour > 18 || isWeekend) {
  alert( 'The office is closed.' ); // it is the weekend
}
```

## OR finds the first truthy value

JavaScript 的特性，or 將由左至右計算布林值，若有一為真，停止計算並返回該值，若皆為錯誤，返回最後一個值。

```javascript
result = value1 || value2 || value3;

alert( null || 0 || 1 ); // 1 (the first truthy value)
alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)
```

1. 假設有一串變數，其中有些是空的有些有存資料，可以用 or 判斷。

   ```javascript
   let currentUser = null;
   let defaultUser = "John";

   let name = currentUser || defaultUser || "unnamed";
   alert( name ); // selects "John" – the first truthy value
   ```
2. 短路檢測：可以用來寫精簡的 if statement 。

   ```javascript
   let x;

   true || (x = 1);
   alert(x); // undefined, because (x = 1) not evaluated

   let x;

   false || (x = 1);
   alert(x); // 1
   ```

## && (AND)

如果參數皆為真，返回 `true`，若有錯誤返回 `false`。

```javascript
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 由左至右尋找第一個錯誤值，若皆無錯誤，返回最後一個值。

```javascript
result = value1 && value2 && value3;

alert( null && 5 ); // null
alert( 1 && 2 && null && 3 ); // null
alert( 1 && 2 && 3 ); // 3, the last one
```

短路檢測：可以用來寫精簡的 if statement 。

```javascript
let x = 1;

(x > 0) && alert( 'Greater than zero!' );

// same
let x = 1;

if (x > 0) {
  alert( 'Greater than zero!' );
}
```

## ! (NOT)

轉換值變成相反布林值。

```javascript
result = !value;

alert( !true ); // false
alert( !0 ); // true
```

!! 轉換類型成布林值。

```javascript
alert( !!"non-empty string" ); // true
alert( !!null ); // false

// same
alert( Boolean("non-empty string") ); // true
alert( Boolean(null) ); // false
```

執行順序：! > && > ||
