JavaScript Standard Style
English • Español (Latinoamérica) • Français • Bahasa Indonesia • Italiano (Italian) • 日本語 (Japanese) • 한국어 (Korean) • Português (Brasil) • 简体中文 (Simplified Chinese) • 繁體中文 (Taiwanese Mandarin)
這是 standard 語法規則的摘要。
最快速掌握 standard 的方法,就是直接安裝並在你的程式碼中開始使用。
規則
-
兩個空白 當作縮排。
eslint:
indentfunction hello (name) { console.log('hi', name) } -
字串用單引號 ,除非要避免跳脫字元。
eslint:
quotesconsole.log('hello there') $("<div class='box'>") -
沒有不必要的變數。
eslint:
no-unused-varsfunction myFunction () { var result = something() // ✗ avoid } -
關鍵字後加空白。
eslint:
keyword-spacingif (condition) { ... } // ✓ ok if(condition) { ... } // ✗ avoid -
函數宣告時,括號前要加空白。
eslint:
space-before-function-parenfunction name (arg) { ... } // ✓ ok function name(arg) { ... } // ✗ avoid run(function () { ... }) // ✓ ok run(function() { ... }) // ✗ avoid -
統一用
===取代==。
例外:obj == null可以用來檢查null || undefined。eslint:
eqeqeqif (name === 'John') // ✓ ok if (name == 'John') // ✗ avoidif (name !== 'John') // ✓ ok if (name != 'John') // ✗ avoid -
中綴運算子(infix operator)前後 必須要加空白。
eslint:
space-infix-ops// ✓ ok var x = 2 var message = 'hello, ' + name + '!'// ✗ avoid var x=2 var message = 'hello, '+name+'!' -
逗號後面要加一個空白。
eslint:
comma-spacing// ✓ ok var list = [1, 2, 3, 4] function greet (name, options) { ... }// ✗ avoid var list = [1,2,3,4] function greet (name,options) { ... } -
把 else 語句 放在大括弧的同一行。
eslint:
brace-style// ✓ ok if (condition) { // ... } else { // ... }// ✗ avoid if (condition) { // ... } else { // ... } -
在 if 語句多於一行時, 加上大括弧。
eslint:
curly// ✓ ok if (options.quiet !== true) console.log('done')// ✓ ok if (options.quiet !== true) { console.log('done') }// ✗ avoid if (options.quiet !== true) console.log('done') -
一定要處理
err參數。eslint:
handle-callback-err// ✓ ok run(function (err) { if (err) throw err window.alert('done') })// ✗ avoid run(function (err) { window.alert('done') }) -
一定要對瀏覽器中的全域變數 加上
window前綴。
除了document、console和navigator可以不用。eslint:
no-undefwindow.alert('hi') // ✓ ok -
不允許多行空白行。
eslint:
no-multiple-empty-lines// ✓ ok var value = 'hello world' console.log(value)// ✗ avoid var value = 'hello world'
console.log(value)
* **三元運算子(ternary operator)** 在多行的情況下,把 `?` 和 `:` 和後面敘述放在同一行。
eslint: [`operator-linebreak`](http://eslint.org/docs/rules/operator-linebreak)
```js
// ✓ ok
var location = env.development ? 'localhost' : 'www.api.com'
// ✓ ok
var location = env.development
? 'localhost'
: 'www.api.com'
// ✗ avoid
var location = env.development ?
'localhost' :
'www.api.com'
-
變數宣告時, 每個宣告要獨自一行。
eslint:
one-var// ✓ ok var silent = true var verbose = true // ✗ avoid var silent = true, verbose = true // ✗ avoid var silent = true, verbose = true -
把條件語句中的賦值加上額外的括弧。 可以更清楚表達這個賦值(
=)是刻意的,而不是原本要打(===)打錯的。eslint:
no-cond-assign// ✓ ok while ((m = text.match(expr))) { // ... } // ✗ avoid while (m = text.match(expr)) { // ... } -
在單行的程式區塊中,前後加入空白。
eslint:
block-spacingfunction foo () {return true} // ✗ avoid function foo () { return true } // ✓ ok -
宣告變數和函式時使用駝峰(camelcase)命名。
eslint:
camelcasefunction my_function () { } // ✗ avoid function myFunction () { } // ✓ ok var my_var = 'hello' // ✗ avoid var myVar = 'hello' // ✓ ok -
不允許行尾逗號。
eslint:
comma-danglevar obj = { message: 'hello', // ✗ avoid } -
逗號必須要放置在該行的最後,不要放到下一行。
eslint:
comma-stylevar obj = { foo: 'foo' ,bar: 'bar' // ✗ avoid } var obj = { foo: 'foo', bar: 'bar' // ✓ ok } -
屬性和它前面的點應該放在同一行
eslint:
dot-locationconsole. log('hello') // ✗ avoid console .log('hello') // ✓ ok -
檔案結尾必須要是一個空白行。
eslint:
eol-last -
呼叫函式時,函式和後面的括弧間不要加空白。
eslint:
func-call-spacingconsole.log ('hello') // ✗ avoid console.log('hello') // ✓ ok -
物件(object)宣告時,在冒號和後面的值中間加空白。
eslint:
key-spacingvar obj = { 'key' : 'value' } // ✗ avoid var obj = { 'key' :'value' } // ✗ avoid var obj = { 'key':'value' } // ✗ avoid var obj = { 'key': 'value' } // ✓ ok -
建構子(constructor)的名稱開頭要大寫。
eslint:
new-capfunction animal () {} var dog = new animal() // ✗ avoid function Animal () {} var dog = new Animal() // ✓ ok -
沒有參數的建構子呼叫時必須要加括號。
eslint:
new-parensfunction Animal () {} var dog = new Animal // ✗ avoid var dog = new Animal() // ✓ ok -
物件的 setter 如果有設定時,getter 也要設定。
eslint:
accessor-pairsvar person = { set name (value) { // ✗ avoid this._name = value } } var person = { set name (value) { this._name = value }, get name () { // ✓ ok return this._name } } -
建構子是繼承來時,一定要呼叫
super;反之,則一定不能呼叫。eslint:
constructor-superclass Dog { constructor () { super() // ✗ avoid } } class Dog extends Mammal { constructor () { super() // ✓ ok } } -
宣告陣列時,用中括弧宣告,不要用陣列建構子。
eslint:
no-array-constructorvar nums = new Array(1, 2, 3) // ✗ avoid var nums = [1, 2, 3] // ✓ ok -
不使用
arguments.callee和arguments.caller。eslint:
no-callerfunction foo (n) { if (n <= 0) return arguments.callee(n - 1) // ✗ avoid } function foo (n) { if (n <= 0) return foo(n - 1) } -
避免重新定義宣告後的類別(class)。
eslint:
no-class-assignclass Dog {} Dog = 'Fido' // ✗ avoid -
避免修改
const宣告的變數。eslint:
no-const-assignconst score = 100 score = 125 // ✗ avoid -
避免在條件語句中使用常數表達式(除了迴圈)。
eslint:
no-constant-conditionif (false) { // ✗ avoid // ... } if (x === 0) { // ✓ ok // ... } while (true) { // ✓ ok // ... } -
正規表達式中不使用控制字元。
eslint:
no-control-regexvar pattern = /\x1f/ // ✗ avoid var pattern = /\x20/ // ✓ ok -
不使用
debugger語句。eslint:
no-debuggerfunction sum (a, b) { debugger // ✗ avoid return a + b } -
不對變數使用
delete。eslint:
no-delete-varvar name delete name // ✗ avoid -
函數不使用相同名稱的參數。
eslint:
no-dupe-argsfunction sum (a, b, a) { // ✗ avoid // ... } function sum (a, b, c) { // ✓ ok // ... } -
類別中不使用相同名稱的成員。
eslint:
no-dupe-class-membersclass Dog { bark () {} bark () {} // ✗ avoid } -
物件中不使用相同名稱的屬性。
eslint:
no-dupe-keysvar user = { name: 'Jane Doe', name: 'John Doe' // ✗ avoid } -
switch中不使用相同名稱的case。eslint:
no-duplicate-caseswitch (id) { case 1: // ... case 1: // ✗ avoid } -
每個模組的引入只用一行。
eslint:
no-duplicate-importsimport { myFunc1 } from 'module' import { myFunc2 } from 'module' // ✗ avoid import { myFunc1, myFunc2 } from 'module' // ✓ ok -
正規表達式中,不用空字元類別。
eslint:
no-empty-character-classconst myRegex = /^abc[]/ // ✗ avoid const myRegex = /^abc[a-z]/ // ✓ ok -
不使用沒有建構出東西的賦值語句。
eslint:
no-empty-patternconst { a: {} } = foo // ✗ avoid const { a: { b } } = foo // ✓ ok -
不使用
eval()。eslint:
no-evaleval( "var result = user." + propName ) // ✗ avoid var result = user[propName] // ✓ ok -
在
catch語句中不要重新定義錯誤。eslint:
no-ex-assigntry { // ... } catch (e) { e = 'new value' // ✗ avoid } try { // ... } catch (e) { const newVal = 'new value' // ✓ ok } -
不要擴展原生物件。
eslint:
no-extend-nativeObject.prototype.age = 21 // ✗ avoid -
避免不必要的函數綁定(bind)。
eslint:
no-extra-bindconst name = function () { getName() }.bind(user) // ✗ avoid const name = function () { this.getName() }.bind(user) // ✓ ok -
避免不必要的布林型別轉換(boolean cast)。
eslint:
no-extra-boolean-castconst result = true if (!!result) { // ✗ avoid // ... } const result = true if (result) { // ✓ ok // ... } -
函式宣告時周圍不加多餘的括弧。
eslint:
no-extra-parensconst myFunc = (function () { }) // ✗ avoid const myFunc = function () { } // ✓ ok -
在
switch中使用break避免把所有的 case 都執行了。eslint:
no-fallthroughswitch (filter) { case 1: doSomething() // ✗ avoid case 2: doSomethingElse() } switch (filter) { case 1: doSomething() break // ✓ ok case 2: doSomethingElse() } switch (filter) { case 1: doSomething() // fallthrough // ✓ ok case 2: doSomethingElse() } -
小數點前後都要有數字。
eslint:
no-floating-decimalconst discount = .5 // ✗ avoid const discount = 0.5 // ✓ ok -
避免重新定義已經宣告過的函式。
eslint:
no-func-assignfunction myFunc () { } myFunc = myOtherFunc // ✗ avoid -
避免重新定義唯讀(read-only)的全域變數。
eslint:
no-global-assignwindow = {} // ✗ avoid -
不要間接使用
eval()。eslint:
no-implied-evalsetTimeout("alert('Hello world')") // ✗ avoid setTimeout(function () { alert('Hello world') }) // ✓ ok -
不要在巢狀架構中宣告函式。
eslint:
no-inner-declarationsif (authenticated) { function setAuthUser () {} // ✗ avoid } -
不要在
RegExp中使用錯誤的表達式句子。eslint:
no-invalid-regexpRegExp('[a-z') // ✗ avoid RegExp('[a-z]') // ✓ ok -
避免不正常的空白。
eslint:
no-irregular-whitespacefunction myFunc () /*<NBSP>*/{} // ✗ avoid -
不使用
__iterator__。eslint:
no-iteratorFoo.prototype.__iterator__ = function () {} // ✗ avoid -
避免 label 和變數有相同的名稱。
eslint:
no-label-varvar score = 100 function game () { score: while (true) { // ✗ avoid score -= 10 if (score > 0) continue score break } } -
避免 label 語法。
eslint:
no-labelslabel: while (true) { break label // ✗ avoid } -
避免非必要的巢狀架構。
eslint:
no-lone-blocksfunction myFunc () { { // ✗ avoid myOtherFunc() } } function myFunc () { myOtherFunc() // ✓ ok } -
縮排避免混雜著空白和 tab。
eslint:
no-mixed-spaces-and-tabs -
除了縮排,不使用多個連續空白。
eslint:
no-multi-spacesconst id = 1234 // ✗ avoid const id = 1234 // ✓ ok -
不使用跳脫字元建立多行字串。
eslint:
no-multi-strconst message = 'Hello \ world' // ✗ avoid -
不要使用
new卻不把結果存下。eslint:
no-newnew Character() // ✗ avoid const character = new Character() // ✓ ok -
不使用
Function建構子。eslint:
no-new-funcvar sum = new Function('a', 'b', 'return a + b') // ✗ avoid -
不使用
Object建構子。eslint:
no-new-objectlet config = new Object() // ✗ avoid -
不使用
new require。eslint:
no-new-requireconst myModule = new require('my-module') // ✗ avoid -
不使用
Symbol建構子。eslint:
no-new-symbolconst foo = new Symbol('foo') // ✗ avoid -
不使用原始包裝器(primitive wrapper instances),比如說 String、Number 和 Boolean。
eslint:
no-new-wrappersconst message = new String('hello') // ✗ avoid -
不要把全域物件當成函式呼叫。
eslint:
no-obj-callsconst math = Math() // ✗ avoid -
宣告數字時不使用八進位的表達式。
eslint:
no-octalconst octal = 042 // ✗ avoid const decimal = 34 // ✓ ok const octalString = '042' // ✓ ok -
字串中不使用八進位的跳脫序列。
eslint:
no-octal-escapeconst copyright = 'Copyright \251' // ✗ avoid -
避免連結字串的時候使用
__dirname和__filename。.eslint:
no-path-concatconst pathToFile = __dirname + '/app.js' // ✗ avoid const pathToFile = path.join(__dirname, 'app.js') // ✓ ok -
避免使用
__proto__. 用getPrototypeOf替代.eslint:
no-protoconst foo = obj.__proto__ // ✗ avoid const foo = Object.getPrototypeOf(obj) // ✓ ok -
避免重新宣告變數。
eslint:
no-redeclarelet name = 'John' let name = 'Jane' // ✗ avoid let name = 'John' name = 'Jane' // ✓ ok -
正規表達式中避免多個空白。
eslint:
no-regex-spacesconst regexp = /test value/ // ✗ avoid const regexp = /test {3}value/ // ✓ ok const regexp = /test value/ // ✓ ok -
在 return 語句中,如果要賦值的話,必須用括弧包住。
eslint:
no-return-assignfunction sum (a, b) { return result = a + b // ✗ avoid } function sum (a, b) { return (result = a + b) // ✓ ok } -
避免把變數賦值給自己。
eslint:
no-self-assignname = name // ✗ avoid -
避免把變數跟自己比較。
esint:
no-self-compareif (score === score) {} // ✗ avoid -
避免使用逗號運算子。
eslint:
no-sequencesif (doSomething(), !!test) {} // ✗ avoid -
不可以把關鍵字遮蔽。
eslint:
no-shadow-restricted-nameslet undefined = 'value' // ✗ avoid -
避免使用稀疏陣列(sparse array)宣告。
eslint:
no-sparse-arrayslet fruits = ['apple',, 'orange'] // ✗ avoid -
不使用 Tab。
eslint:
no-tabs -
一般字串不使用樣板語法。
eslint:
no-template-curly-in-stringconst message = 'Hello ${name}' // ✗ avoid const message = `Hello ${name}` // ✓ ok -
super()要在this之前被呼叫。eslint:
no-this-before-superclass Dog extends Animal { constructor () { this.legs = 4 // ✗ avoid super() } } -
錯誤時只拋出(
throw)Error型態.eslint:
no-throw-literalthrow 'error' // ✗ avoid throw new Error('error') // ✓ ok -
行尾不加空白。
eslint:
no-trailing-spaces -
避免用
undefined初始化。eslint:
no-undef-initlet name = undefined // ✗ avoid let name name = 'value' // ✓ ok -
避免一成不變的循環條件。
eslint:
no-unmodified-loop-conditionfor (let i = 0; i < items.length; j++) {...} // ✗ avoid for (let i = 0; i < items.length; i++) {...} // ✓ ok -
避免不必要的三元運算子。
eslint:
no-unneeded-ternarylet score = val ? val : 0 // ✗ avoid let score = val || 0 // ✓ ok -
避免在
return、throw、continue和break後面有不會被執行的程式碼。eslint:
no-unreachablefunction doSomething () { return true console.log('never called') // ✗ avoid } -
避免在
finally裡面加入控制流的語句。eslint:
no-unsafe-finallytry { // ... } catch (e) { // ... } finally { return 42 // ✗ avoid } -
關係運算子的左運算元不可以被否定。
eslint:
no-unsafe-negationif (!key in obj) {} // ✗ avoid -
避免不必要的
.call()和.apply()用法。eslint:
no-useless-callsum.call(null, 1, 2, 3) // ✗ avoid -
避免物件中使用多餘計算的屬性。
eslint:
no-useless-computed-keyconst user = { ['name']: 'John Doe' } // ✗ avoid const user = { name: 'John Doe' } // ✓ ok -
避免不必要的建構子。
eslint:
no-useless-constructorclass Car { constructor () { // ✗ avoid } } -
避免不必要的跳脫字元。
eslint:
no-useless-escapelet message = 'Hell\o' // ✗ avoid -
避免在 import、export 和 destructured 時,不必要的重新命名。
eslint:
no-useless-renameimport { config as config } from './config' // ✗ avoid import { config } from './config' // ✓ ok -
避免在屬性前加空白。
eslint:
no-whitespace-before-propertyuser .name // ✗ avoid user.name // ✓ ok -
避免使用
with。eslint:
no-withwith (val) {...} // ✗ avoid -
維持物件屬性宣告時,換行的一致性。
eslint:
object-property-newlineconst user = { name: 'Jane Doe', age: 30, username: 'jdoe86' // ✗ avoid } const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' } // ✓ ok const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' } // ✓ ok -
程式區塊前後不要加空行。
eslint:
padded-blocksif (user) { // ✗ avoid const name = getName() } if (user) { const name = getName() // ✓ ok } -
展開運算子(spread operator)前不要加空格。
eslint:
rest-spread-spacingfn(... args) // ✗ avoid fn(...args) // ✓ ok -
分號後面要加空格,前面不要加。
eslint:
semi-spacingfor (let i = 0 ;i < items.length ;i++) {...} // ✗ avoid for (let i = 0; i < items.length; i++) {...} // ✓ ok -
程式區塊前要加空格。
eslint:
space-before-blocksif (admin){...} // ✗ avoid if (admin) {...} // ✓ ok -
括弧內不要加空格。
eslint:
space-in-parensgetName( name ) // ✗ avoid getName(name) // ✓ ok -
一元運算子後面要加空格。
eslint:
space-unary-opstypeof!admin // ✗ avoid typeof !admin // ✓ ok -
註解前要加空格。
eslint:
spaced-comment//comment // ✗ avoid // comment // ✓ ok /*comment*/ // ✗ avoid /* comment */ // ✓ ok -
樣板語法不加空格。
eslint:
template-curly-spacingconst message = `Hello, ${ name }` // ✗ avoid const message = `Hello, ${name}` // ✓ ok -
用
isNaN()檢查是否為NaN.eslint:
use-isnanif (price === NaN) { } // ✗ avoid if (isNaN(price)) { } // ✓ ok -
typeof比較的對象一定要是有效的字串。eslint:
valid-typeoftypeof name === 'undefimed' // ✗ avoid typeof name === 'undefined' // ✓ ok -
立即執行的函數需要被包起來。
eslint:
wrap-iifeconst getName = function () { }() // ✗ avoid const getName = (function () { }()) // ✓ ok const getName = (function () { })() // ✓ ok -
yield*中的*前後要加空格。eslint:
yield-star-spacingyield* increment() // ✗ avoid yield * increment() // ✓ ok -
避免使用 Yoda 語法。
eslint:
yodaif (42 === age) { } // ✗ avoid if (age === 42) { } // ✓ ok
分號
-
eslint:
semiwindow.alert('hi') // ✓ ok window.alert('hi'); // ✗ avoid -
絕對不要用
(、[或`當開頭,這是不用分號 唯一 可能遇到的問題。eslint:
no-unexpected-multiline// ✓ ok ;(function () { window.alert('ok') }()) // ✗ avoid (function () { window.alert('ok') }())// ✓ ok ;[1, 2, 3].forEach(bar) // ✗ avoid [1, 2, 3].forEach(bar)// ✓ ok ;`hello`.indexOf('o') // ✗ avoid `hello`.indexOf('o')注意:如果你通常會這樣寫程式,你也許是太想讓自己的程式碼看起來比別人聰明了。
一些看似很厲害的縮寫通常是對讀程式碼的人不友善的,你應該盡量把程式碼寫的清楚而且可讀性高。
比起這種寫法:
;[1, 2, 3].forEach(bar)這種寫法是更推薦的:
var nums = [1, 2, 3] nums.forEach(bar)
延伸閱讀
- An Open Letter to JavaScript Leaders Regarding Semicolons
- JavaScript Semicolon Insertion – Everything you need to know
還有延伸影片:
所有當今流行的程式語言都使用 AST 為基礎來做程式碼的最小化(code minification),所以可以完美的處理沒有分號的 JavaScript。
節選自 "An Open Letter to JavaScript Leaders Regarding Semicolons":
[依賴自動插入分號]非常的安全,而且合語法的 JavaScript 是跨瀏覽器都相容的。Closure compiler、yuicompressor、packer 和 jsmin 都可以正確的最小化,所以沒有效能的問題。
我很抱歉,這個語言社群的領導者們給你們謊言和恐懼,而不是教育你們。這是很羞恥的。我建議你們去學習一下 JavaScript 語句到底是如何結束的(還有哪些是不會結束的),如此你們就可以寫下漂亮的程式碼。
一般來說,
\n結束一個語句,除非: 1. 這個語句有未結束的括弧、陣列、或物件,或其他不正常結束的句子(比如說用.或,結尾) 2. 該行的內容是--或++(這種情況下,他會減少或增加下一個遇到的元素) 3. 該行是for()、while()、do、if()或else,而還沒有出現{4. 隔行的開頭是[、(、+、*、/、-、,、.或其他一定要兩個運算元的一元運算子。第一種是非常顯而易見的。即使 JSLint 也允許 JSON 、有括弧的建構子和
var誇多行語句的宣告可以有\n在其中。第二種是非常奇怪的語法。我現實中沒有看過這種例子(除了在這類討論之外),會想寫出
i\n++\nj這種奇怪的程式碼,這會被編譯器解讀成i; ++j,而非i++; j。第三種就非常好理解。
if (x)\ny()和if (x) { y() }是相同的。建構子會一直往後找到一個區塊或一個語句。
;是一個合法的 JavaScript 語句。所以if(x);和if(x){}是相同的,代表 “如果 x, 什麼都不要做。” 當迴圈的判斷和更新是同一個函式的時候,有時候會被用到。不太常見,但是也不是沒看過。第四種是那些常常被提到說:「看!你需要分號吧!」的例子。但是其實這很簡單可以避免,只要在該行開始前加個分號就好了。舉例來說,如果你原本要這樣寫:
foo(); [1,2,3].forEach(bar);你其實可以這樣寫:
foo() ;[1,2,3].forEach(bar)這樣的好處是這些前綴字是很好被察覺的,你可以很容易發現那些
(或[開頭而沒有分號的地方。