# Languages that compiles to JavaScript, its advantages/disadvantages ### 題目: > What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript? ## 轉譯(compile)成 JavaScript 的語言? 舉例來說 - CoffeeScript - Elm - ClojureScript - PureScript - **TypeScript** (現在仍然流行) 除了 TypeScript 以外,這些語言的興衰與 ES2015(ES6) 推出有蠻大的關係 ### 以 CoffeeScript 為例,這些語言可能幫我們達成什麼? (以下是 *10年前* 撰寫談論 CoffeeScript 書作者的看法) - 在 CoffeeScript 中, variables are auto-scoped,可以避免原生 JavaScript 中在同一個或不同檔案之間 `var` 被意外複寫的狀況 (因為`var` 可以重新宣告) :::spoiler 舉例: 在 `foo.coffee` 這個檔案裡面,如果我們寫了: ``` x = 'stringy string' ``` 而在 `bar.coffee` 這個檔案裡面,我們寫了: ``` x = 42 ``` 編譯(compile)這兩個檔案成 JavaScript,並且 concatenate `foo.js` with `bar.js` for deployment 會得到 ```JavaScript= (function() { var x; x = 'stringy string'; ... }).call(this); (function() { var x; x = 42; ... }).call(this); ``` 所以 - `foo.coffee` 中的 `x` 和 `bar.coffee` 中的`x` 彼此會完全分離 - Important feature of CoffeeScript: **Variables never leak from one `.coffee` file to another** ::: 不過,ES6 出現了 `let` ,重複宣告會報錯,所以... - `->` 的寫法比 `function(){}` 簡單方便很多, 尤其在callback 當中,另外 Semantic indentation 讓巢狀的 callbacks 易讀性很高 - 一些 if statement 更簡潔易讀(更像英文)的語法 CoffeeScript 中: - `unless x` 被 compile 成 `(!x)` - `if x?` 被 compile 成 `(x != null)` *A great library like* `Underscore.js` *can take care of some of these problems, but not all.* <br> ### TypeScript 是什麼 > **TypeScript is JavaScript with syntax for types.** > A strongly typed programming language which builds on JavaScript giving you better tooling at any scale. (待補充) ## 這些 Compile 成 JavaScript 語言的優缺點? ### 優點: - 修復了 JavaScript 中的一些長期問題,拋棄了 JavaScript 的一些 anti-pattern 。 - 在 JavaScript 的基礎上提供一些語法糖,使我们能夠編寫更簡潔的 code( ES5 之前缺乏語法糖的支持,但 ES2015 開始有非常多的支持) - 對於需要長時間維護的大型專案,靜態類型非常好用(此點針對 TypeScript)。 ### 缺點: - 由於瀏覽器實際上只 run JavaScript,所以需要 build 、compile 轉譯成 JavaScript 的過程 - Debugging can be a pain if your source maps do not map nicely to your pre-compiled source - 學習成本。對於公司來說,選擇例如 TypeScript 用在專案上面,會增加團隊成本 - 某些語言的 community 比較小,所以對應的資源、課程、書籍和工作比較難找到 - 可能缺乏 IDE(編輯器)的支持。 - 始终落後於最新 JavaScript 的標準。 - Developer 應該仍然要清楚這些語言會被編譯成怎麼樣的 JavaScript 內容,因為那才是真實在 browser 上 run 的 code <br> ## 補充: JavaScript ES6 新增了什麼 此處列出常用: - Block Scope 塊級作用域 - `let`, `const` - Arrow Functions 箭頭函式 - Default Function Parameters 函數預設參數 - Spread/Rest Operator 展開/其餘運算子 - Promise 物件 - Array and Object Destructuring 陣列和物件的解構賦值 - Object Literal Extensions 物件實字擴展 - Template Literals 模版字符串 - for...of 迴圈 - class 關鍵字 現在已經到 ES10 了,不過後續是比較小的 features 陸續增加,沒有像 ES6 (ES2015) 這麼大幅度的變革 **** ### 重要參考資料: [JavaScript ES6 介紹](https://www.fooish.com/javascript/ES6/)