# JavaScript Coding Convention
參考: [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html)
### 文件名
文件名必須全部小寫,並且可以包含下劃線 ( _) 或破折號 ( -),不能包含其他標點符號。文件名的擴展名必須是.js.
## Formatting
### 括號
(”或“)”的關鍵字必須在其前後提供空格
```
let integer = function (
value,
default_value
) {
value = resolve(value);
return (10*value);
};
```
#### 大括號
所有控制結構 (i.e. if, else, for, do, while, as well as any others)都需使用
* 左大括號之前沒有換行符。
* 左大括號後換行。
* 右大括號之前換行。
* Block indentation +2 spaces
```
method(foo) {
if (condition(foo)) {
try {
// Note: this might fail.
something();
} catch (err) {
recover();
}
}
}
}
```
如果很短,一行不帶大括號 :
`if (n < 0) alert(Power ${n} is not supported`);
### statements
* 需要分號
每個語句都必須以分號結束。禁止依賴自動分號插入。
* 列數限制:80
JavaScript 代碼的列限制為 80 個字符
* 在哪里中斷
優先選擇在較高的語法層級上斷行
Preferred:
```
currentEstimate =
calc(currentEstimate + x * currentEstimate) /
2.0;
```
Discouraged:
```
currentEstimate = calc(currentEstimate + x *
currentEstimate) / 2.0;
```
當在運算符號處斷行時,斷行在符號之後。(注意這不是 Google Java 風格中所使用的方法。)
這不適用於點號(.),因為點號實際上不是運算符
方法或建構函式名稱與後面的開括號(())保持連接。
逗號(,)與其前面的標記保持連接。
* 縮進連續行至少增加 4 個空格
```
switch (animal) {
case Animal.BANDERSNATCH:
handleBandersnatch();
break;
case Animal.JABBERWOCK:
handleJabberwock();
break;
default:
throw new Error('Unknown animal');
}
```
* 陣列統一使用 [],不可用 array()
```
// Good
$arr = [];
// Bad
$arr = array();
```
#### Spread operator
將一個或多個其他可迭代對像中的元素擴展,應該使用展開運算符,而不是使用Array.prototype
```
[...foo] // preferred over Array.prototype.slice.call(foo)
[...foo, ...bar] // preferred over foo.concat(bar)
```
## Language features
#### 使用const和let
使用const或聲明所有局部變量let。默認情況下使用 const,除非需要重新分配變量。var 不得使用該關鍵字。
#### 每個聲明一個變量
每個局部變量聲明僅聲明一個變量:EX:let a = 1, b = 2 (不被使用)。
### variables/functions 命名
* Case styles :主要使用 Camel Case (pageCount) 駝峰命名法
| Prose form | Correct | Incorrect |
| -------- | -------- | -------- |
| XML HTTP request | XmlHttpRequest | XMLHTTPRequest |
| new customer ID | newCustomerId | newCustomerID |
* Pascal Case (PageCount) ,Snake Case ( page_count)

* 不要用縮寫:

* Booleans: 可以用 is 或 has 開頭

* Functions: 函式若是做一些動作後輸出,命名應該是動作 + 做什麼事

//bad
let bark=false;
//good
var isBark=false;
//bad
var owner=true;
//good
var hasOwner=true;
//bad
function name(dogName,owerName){
return '${dogname} ${ownerName}';
}
//good
function getName(dogName,owerName){
return '${dogname} ${ownerName}';
}