# 型別與運算子 ## Dynamic Type (弱型別) You don't tell the engine what type of data a variable holds, it figures it out while your code is running - Variables can hold different types of values because it's all figured out during execution ``` //Static Typing bool isNew = 'hello'; // an error //Dynamic Typing Var isNew = true; // no errors isNew = 'yup'; isNew = 1 ``` ### Primitive Types (純值、基本型別) A type of data that represents a single value. That is, not a object JavaScript 有六種純值(Primitive Type)的型別。 - Undefined - Undefined represents lack of existence (you shouldn't set a variable to this),也是 Javascript 給所有變數的初始值。 - Null - Null represents lack of existence (you can set a variable to this) - Boolean - true or false - Number - *Floating point* number (there's always some decimals). Unlike other programming languags, there's only one 'number' type... and it can make math weird. - String - A sequence of characters (both '' and "" can be used) - Symbol - Used in ES6 (the nex version of Javascript) We won't talk about this here... ## Operator (運算子) A special function that is syntactically (written) differently Generally, operators take two parameters and return one result. 運算子都是函數 ### Operator precedence and associativity (運算子的優先性與相依性) #### Operator precedence Which operator function gets called first Functions are called in order of precedence (HIGHER precedence wins) #### Associativity What order operator functions get called in: left-to-right or right-to-left When functions have the same precedence [MDN - 運算子優先序](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) ### Coercion (強制型轉) Converting a value from one type to another This happens quite often in Javascript because it's dynamically typed. ```javascript= var a = 1 + '2' console.log(a) // 12 (String) ``` ### Comparision operators 應該永遠使用 `===` 來比較是否相同,除非特殊情況 [MDN - 相等性比較](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) ### Existence and booleans [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) ```javascript= var a; // do something.. if(a){ console.log('a is truthy') }else{ console.log('a is falsy') } ``` ### Default values ```javascript= function greet(name){ name = name || '<Your name here>' console.log('Hello' + name) } greet() // Hello <Your name here> ``` ###### tags: `WierdJavascript`