# Ternary(Conditional)operator 三元(條件) 運算子 > **問題:** > Why is it called a **Ternary expression**, what does the word "Ternary" indicate? ##### Ternary 三元 consisting of three parts ##### Expressions 表達式 (運算式) a unit of code that **results in a value** <br > ### 運算元 operand v.s. 運算子 operator #### 二元運算子(Binary operator) ``` operand1 operator operand2 運算元1 運算子 運算元2 ``` 例如:`3 + 4` , `someArray.length === 0` #### 一元運算子 (unary operator) ``` operand operator (運算元 運算子) 或 operator operand (運算子 運算元) ``` 例如:`x++` ; `x` 是 3,`-x` 回傳 `-3` [MDN:運算式與運算子 ](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Expressions_and_Operators) <br > ## 三元運算子 Ternary Operator (Conditional operator 條件運算子) ``` condition ? exprIfTrue : exprIfFalse ``` >「條件運算子」是 JavaScript 唯一用到 **三個運算元(operand)** 的運算子(operator) - 這個運算子常常被用來當作 `if/else` 的簡潔寫法 - 在 condition 後面會跟著 `?` - 如果 condition 是 **truthy**, `:` **前**的表達式會被執行 - 如果 condition 是 **falsy**,在 `:` **後**的表達式會被執行, #### 基本範例 ```javascript const age = 26; const beverage = (age >= 18) ? "Beer" : "Coke"; console.log(beverage); // "Beer" ``` 常被用來處理 `null` : ```javascript function greeting(person) { var name = person ? person.name : "stranger"; return "Howdy, " + name; } console.log(greeting({name: 'Alice'})); // "Howdy, Alice" console.log(greeting(null)); // "Howdy, stranger" ``` #### React 開發使用實例 決定 className 來改變 style : ```jsx <div className={isEditMode ? 'bg-gray-50' : 'bg-white'}></div> ``` 決定要 render 哪一個 component : ```jsx export default function Template({isEditMode}) { return ( <div style={{ marginTop: '80px' }}> {isEditMode ? <EditIntroTemplate /> : <PreviewIntroTemplate />} </div> ); } ``` >**答:** >「Ternary」表示接受**三個運算元**: >- 判斷條件 condition >- then 表達式 (expression) >- else 表達式 (expression) <br > ### 條件鏈 (Conditional chains) ```javascript function example(…) { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4; } // Equivalent to: function example(…) { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return value4; } } ``` <br > **** ## Truthy v.s. Falsy ### Falsy >A falsy value is a value that is considered false when **encountered in a Boolean context**. JavaScript 在需要用到 boolean 值的上下文中使用強制類型轉換(Type Conversion )將值轉換為 boolean value,例如 conditionals and loops。 | 常見 falsy values 列表| | -------------------------- | | `false`| | 0, -0 | | `""` , `''` , `` (空字串) | |`null`| |`undefined`| |`NaN`| [MDN: Falsy ](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) ### truthy >**All values are truthy unless they are defined as falsy** ```javascript if ({}) if ([]) // 這兩個是最常被誤以為是 falsy 的 if (42) if ("0") if ("false") if (new Date()) if (Infinity) ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up