**Truthy, falthy, ternary operator / Short-circuit evaluation / Optional Chaining operator / Nullish coalescing operator(請搭配程式範例)** --- ### [簡報連結請點我~](https://drive.google.com/file/d/1NDxS0n9lZ-4flVfylFbegNkBvoC9gXt6/view?usp=sharing) ### Truthy and falsy * 每個element都隸屬於一個data type,同時也有隱含的boolean屬性,也就是被轉換成布林值為true或false的屬性 * 隱含有false屬性的falsy家族:false、0、-0、空字串、null(空值、沒有值)、undefined(變數沒有被宣告、已經宣告但沒有賦值)、NaN(not a number)(在javascript中無法被明確定義的數值) * 除了falsy家族之外的,都是truthy,特別注意: "0", "false", [], {}, empty等都是truthy! ### 寬鬆比較(= =) 與 嚴格比較 (= = =) * 寬鬆比較會對變數做轉換型別的動作(coercion),而嚴格比較中是不允許轉換型別的 * 寬鬆比較時的型別轉換:字串內放數字會轉為number型別、true跟false會轉換成1與0 * 寬鬆比較時falsy家族間的互相比較:空字串、0、false三者可相等、null與undefined可相等 * 嚴格比較中型別與值皆要相等才會成立 * 針對非Javascript原始型別的物件如Array、Object之比較 * 是針對reference進行比較,而非針對value進行比較 * example: ``` let a = [1,2,3] let b = [1,2,3] a == b // false b = a 將記憶體位置指向相同地方 a == b // true ``` ### Ternary Operator 三元運算子 * syntax架構:condition? value1:value2 * 範例可以直接看簡報OWO ### Short circuit evaluation 短路求值 * 以最短路徑求值,是一種邏輯運算的求值策略,當最終結果已經可以確認時,直接終止 * 搭配 &&(AND)與 || (OR)邏輯運算子使用 * &&:左右兩邊的值皆需符合要求才成立,若檢查左邊的已經不符合要求,直接不成立,不會再往右 * | |: 左右兩邊的值只需有其中一個符合要求便成立,若檢查左邊的已經符合要求,直接成立,不會再去檢查右邊的值 * 範例可以直接看簡報OWO ### Optional Chaining Operator(?.) 可選串連運算子 * 在存取某個變數上的 property 或是呼叫某個函數時,可能會因為該變數為 null 或 undefined 而拋出 TypeError * 透過Optional Chaining Operator可避免TypeError與巢狀檢測的問題 * 允許深層的key, value查詢,若key不存在則直接回傳undefined,不會再繼續進行 * 範例可以直接看簡報OWO ### Nullish coalescing operator(??) 空值合併運算子 * 回傳第一個defined的值(跟||的差異在於:||是回傳第一個truthy值) * 除了null與undefined外其他東西都是defined * 當需要取用部分falsy值(如0)時可以使用?? instead of | | * 範例可以直接看簡報OWO ### Dive deeper into the topic * Truthy and Falsy * https://www.sitepoint.com/javascript-truthy-falsy/ * Ternary Operator * https://www.javascripttutorial.net/javascript-ternary-operator/ * https://www.scaler.com/topics/javascript/ternary-operator-javascript/ * Short Circuit Evaluation * https://www.geeksforgeeks.org/short-circuit-evaluation-in-programming/ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR * Optional Chaining Operator * https://javascript.info/optional-chaining * https://www.javascripttutorial.net/es-next/javascript-optional-chaining-operator/ * Nullish Coalescing Operator * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator * https://levelup.gitconnected.com/understand-the-nullish-coalescing-operator-coming-in-es2020-2d1c6df1765f