Back to Standard

JavaScript Standard Style

docs/RULES-ja.md

17.1.235.9 KB
Original Source

JavaScript Standard Style

<p align="center"> <a href="/docs/RULES-en.md">English</a> • <a href="/docs/RULES-esla.md">Español (Latinoamérica)</a> • <a href="/docs/RULES-fr.md">Français</a> • <a href="/docs/RULES-id.md">Bahasa Indonesia</a> • <a href="/docs/RULES-iteu.md">Italiano (Italian)</a> • <a href="/docs/RULES-ja.md">日本語 (Japanese)</a> • <a href="/docs/RULES-kokr.md">한국어 (Korean)</a> • <a href="/docs/RULES-ptbr.md">Português (Brasil)</a> • <a href="/docs/RULES-zhcn.md">简体中文 (Simplified Chinese)</a> • <a href="/docs/RULES-zhtw.md">繁體中文 (Taiwanese Mandarin)</a> </p>

これは、standardなJavaScriptのルールの概要です。

standardを学ぶための最も良い方法は、ただインストールしてあなたのコードで試してみることです。

ルール

  • インデントには2個のスペースを使用する。

    eslint: indent

    js
    function hello (name) {
      console.log('hi', name)
    }
    
  • エスケープを避ける場合を除いて、文字列にはシングルクォートを使用する。

    eslint: quotes

    js
    console.log('hello there')    // ✓ ok
    console.log("hello there")    // ✗ avoid
    console.log(`hello there`)    // ✗ avoid
    
    $("<div class='box'>")        // ✓ ok
    console.log(`hello ${name}`)  // ✓ ok
    
  • 未使用の変数は定義しない。

    eslint: no-unused-vars

    js
    function myFunction () {
      var result = something()   // ✗ avoid
    }
    
  • キーワードの後にはスペースを入れる。

    eslint: keyword-spacing

    js
    if (condition) { ... }   // ✓ ok
    if(condition) { ... }    // ✗ avoid
    
  • 関数宣言の括弧の前にはスペースを入れる。

    eslint: space-before-function-paren

    js
    function name (arg) { ... }   // ✓ ok
    function name(arg) { ... }    // ✗ avoid
    
    run(function () { ... })      // ✓ ok
    run(function() { ... })       // ✗ avoid
    
  • 常に==ではなく===を使用する。

    例外: obj == nullnull || undefinedをチェックするために許容されます。

    eslint: eqeqeq

    js
    if (name === 'John')   // ✓ ok
    if (name == 'John')    // ✗ avoid
    
    js
    if (name !== 'John')   // ✓ ok
    if (name != 'John')    // ✗ avoid
    
  • 演算子の間には 空白を入れる。

    eslint: space-infix-ops

    js
    // ✓ ok
    var x = 2
    var message = 'hello, ' + name + '!'
    
    js
    // ✗ avoid
    var x=2
    var message = 'hello, '+name+'!'
    
  • カンマの後にはスペース を置くことを推奨。

    eslint: comma-spacing

    js
    // ✓ ok
    var list = [1, 2, 3, 4]
    function greet (name, options) { ... }
    
    js
    // ✗ avoid
    var list = [1,2,3,4]
    function greet (name,options) { ... }
    
  • else文は 波括弧と 同じ行に 書く。

    eslint: brace-style

    js
    // ✓ ok
    if (condition) {
      // ...
    } else {
      // ...
    }
    
    js
    // ✗ avoid
    if (condition) {
      // ...
    }
    else {
      // ...
    }
    
  • 複数行のif文には、 波括弧を付ける。

    eslint: curly

    js
    // ✓ ok
    if (options.quiet !== true) console.log('done')
    
    js
    // ✓ ok
    if (options.quiet !== true) {
      console.log('done')
    }
    
    js
    // ✗ avoid
    if (options.quiet !== true)
      console.log('done')
    
  • 関数のパラメーターに err がある場合、常に処理する。

    eslint: handle-callback-err

    js
    // ✓ ok
    run(function (err) {
      if (err) throw err
      window.alert('done')
    })
    
    js
    // ✗ avoid
    run(function (err) {
      window.alert('done')
    })
    
  • ブラウザのグローバルオブジェクトは /* global */コメントで宣言する。

    例外: windowdocumentnavigator

    openlengtheventnameのような不適切な名前のグローバルオブジェクトの誤用を防ぎます。

    js
    /* global alert, prompt */
    
    alert('hi')
    prompt('ok?')
    

    明示的にwindowの関数またはプロパティを参照するのも良いですが、そのようなコードはwindowの代わりにselfを使うWorkerでは動作しません。

    eslint: no-undef

    js
    window.alert('hi')   // ✓ ok
    
  • 複数行の空行はしないこと。

    eslint: no-multiple-empty-lines

    js
    // ✓ ok
    var value = 'hello world'
    console.log(value)
    
    js
    // ✗ avoid
    var value = 'hello world'
    
    
    console.log(value)
    
  • 複数行の三項演算子では、?:を各行に書いてください。

    eslint: 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'
    
  • var宣言では、 各宣言を個別に書く。

    eslint: one-var

    js
    // ✓ ok
    var silent = true
    var verbose = true
    
    // ✗ avoid
    var silent = true, verbose = true
    
    // ✗ avoid
    var silent = true,
        verbose = true
    
  • 条件式での代入は追加の括弧でラップする。 これは、式が等価演算子(===)のタイプミスではなく意図的な代入(=)であることを明確にします。

    eslint: no-cond-assign

    js
    // ✓ ok
    while ((m = text.match(expr))) {
      // ...
    }
    
    // ✗ avoid
    while (m = text.match(expr)) {
      // ...
    }
    
  • 単一行ブロックの内側にはスペースを入れる。

    eslint: block-spacing

    js
      function foo () {return true}    // ✗ avoid
      function foo () { return true }  // ✓ ok
    
  • 変数と関数の命名にはキャメルケースを使う。

    eslint: camelcase

    js
      function my_function () { }    // ✗ avoid
      function myFunction () { }     // ✓ ok
    
      var my_var = 'hello'           // ✗ avoid
      var myVar = 'hello'            // ✓ ok
    
  • 末尾のカンマはしないこと。

    eslint: comma-dangle

    js
      var obj = {
        message: 'hello',   // ✗ avoid
      }
    
  • カンマは必ず行末に置く

    eslint: comma-style

    js
      var obj = {
        foo: 'foo'
        ,bar: 'bar'   // ✗ avoid
      }
    
      var obj = {
        foo: 'foo',
        bar: 'bar'   // ✓ ok
      }
    
  • ドットはプロパティと同じ行に置くことを推奨。

    eslint: dot-location

    js
      console.
        log('hello')  // ✗ avoid
    
      console
        .log('hello') // ✓ ok
    
  • ファイルは必ず改行で終わる。

    eslint: eol-last

  • 関数の識別子とその呼び出しの間にスペースを置かない。

    eslint: func-call-spacing

    js
    console.log ('hello') // ✗ avoid
    console.log('hello')  // ✓ ok
    
  • オブジェクトリテラルのコロンと値の間にスペースを入れる。

    eslint: key-spacing

    js
    var obj = { 'key' : 'value' }    // ✗ avoid
    var obj = { 'key' :'value' }     // ✗ avoid
    var obj = { 'key':'value' }      // ✗ avoid
    var obj = { 'key': 'value' }     // ✓ ok
    
  • コストラクタ名は必ず大文字で始める。

    eslint: new-cap

    js
    function animal () {}
    var dog = new animal()    // ✗ avoid
    
    function Animal () {}
    var dog = new Animal()    // ✓ ok
    
  • 引数なしコンストラクタは必ず括弧付きで実行する。

    eslint: new-parens

    js
    function Animal () {}
    var dog = new Animal    // ✗ avoid
    var dog = new Animal()  // ✓ ok
    
  • setterが定義されている場合、getterを必ず含むこと。

    eslint: accessor-pairs

    js
    var 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-super

    js
    class Dog {
      constructor () {
        super()             // ✗ avoid
        this.legs = 4
      }
    }
    
    class Dog extends Animal {
      constructor () {      // ✗ avoid
        this.legs = 4
      }
    }
    
    class Dog extends Animal {
      constructor () {
        super()             // ✓ ok
        this.legs = 4
      }
    }
    
  • 配列初期化にはArrayコンストラクタではなく配列リテラルを使用する。

    eslint: no-array-constructor

    js
    var nums = new Array(1, 2, 3)   // ✗ avoid
    var nums = [1, 2, 3]            // ✓ ok
    
  • arguments.calleearguments.callerは使用しない。

    eslint: no-caller

    js
    function foo (n) {
      if (n <= 0) return
    
      arguments.callee(n - 1)   // ✗ avoid
    }
    
    function foo (n) {
      if (n <= 0) return
    
      foo(n - 1)                // ✓ ok
    }
    
  • クラス宣言した名前を上書きしない。

    eslint: no-class-assign

    js
    class Dog {}
    Dog = 'Fido'    // ✗ avoid
    
  • constを使って宣言された変数を上書きしない。

    eslint: no-const-assign

    js
    const score = 100
    score = 125       // ✗ avoid
    
  • 条件式に定数を使用しない(ループを除く)。

    eslint: no-constant-condition

    js
    if (false) {    // ✗ avoid
      // ...
    }
    
    if (x === 0) {  // ✓ ok
      // ...
    }
    
    while (true) {  // ✓ ok
      // ...
    }
    
  • 正規表現に制御文字は禁止。

    eslint: no-control-regex

    js
    var pattern = /\x1f/    // ✗ avoid
    var pattern = /\x20/    // ✓ ok
    
  • debugger文は禁止。

    eslint: no-debugger

    js
    function sum (a, b) {
      debugger      // ✗ avoid
      return a + b
    }
    
  • delete演算子を変数に使うことは禁止。

    eslint: no-delete-var

    js
    var name
    delete name     // ✗ avoid
    
  • 関数の引数の重複は禁止。

    eslint: no-dupe-args

    js
    function sum (a, b, a) {  // ✗ avoid
      // ...
    }
    
    function sum (a, b, c) {  // ✓ ok
      // ...
    }
    
  • クラスのメンバーに重複する名前は禁止。

    eslint: no-dupe-class-members

    js
    class Dog {
      bark () {}
      bark () {}    // ✗ avoid
    }
    
  • オブジェクトリテラルに重複するキーは禁止。

    eslint: no-dupe-keys

    js
    var user = {
      name: 'Jane Doe',
      name: 'John Doe'    // ✗ avoid
    }
    
  • switch文に重複するラベルは禁止。

    eslint: no-duplicate-case

    js
    switch (id) {
      case 1:
        // ...
      case 1:     // ✗ avoid
    }
    
  • ひとつのモジュールにはひとつのimport文を使用する。

    eslint: no-duplicate-imports

    js
    import { myFunc1 } from 'module'
    import { myFunc2 } from 'module'          // ✗ avoid
    
    import { myFunc1, myFunc2 } from 'module' // ✓ ok
    
  • 正規表現に空の文字クラスは禁止。

    eslint: no-empty-character-class

    js
    const myRegex = /^abc[]/      // ✗ avoid
    const myRegex = /^abc[a-z]/   // ✓ ok
    
  • 空の分割代入は禁止。

    eslint: no-empty-pattern

    js
    const { a: {} } = foo         // ✗ avoid
    const { a: { b } } = foo      // ✓ ok
    
  • eval()は使用禁止。

    eslint: no-eval

    js
    eval( "var result = user." + propName ) // ✗ avoid
    var result = user[propName]             // ✓ ok
    
  • catch節で例外の再代入は禁止。

    eslint: no-ex-assign

    js
    try {
      // ...
    } catch (e) {
      e = 'new value'             // ✗ avoid
    }
    
    try {
      // ...
    } catch (e) {
      const newVal = 'new value'  // ✓ ok
    }
    
  • ネイティブオブジェクトの拡張禁止。

    eslint: no-extend-native

    js
    Object.prototype.age = 21     // ✗ avoid
    
  • 不要な関数バインディングをしない。

    eslint: no-extra-bind

    js
    const name = function () {
      getName()
    }.bind(user)    // ✗ avoid
    
    const name = function () {
      this.getName()
    }.bind(user)    // ✓ ok
    
  • 不要なbooleanのキャストをしない。

    eslint: no-extra-boolean-cast

    js
    const result = true
    if (!!result) {   // ✗ avoid
      // ...
    }
    
    const result = true
    if (result) {     // ✓ ok
      // ...
    }
    
  • 関数式の周囲の不要な括弧は禁止。

    eslint: no-extra-parens

    js
    const myFunc = (function () { })   // ✗ avoid
    const myFunc = function () { }     // ✓ ok
    
  • switch文のcase節でフォールスルーを防ぐためbreakを使用する。

    eslint: no-fallthrough

    js
    switch (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-decimal

    js
    const discount = .5      // ✗ avoid
    const discount = 0.5     // ✓ ok
    
  • 関数宣言を上書きしない。

    eslint: no-func-assign

    js
    function myFunc () { }
    myFunc = myOtherFunc    // ✗ avoid
    
  • 読み取り専用のグローバル変数を上書きしない。

    eslint: no-global-assign

    js
    window = {}     // ✗ avoid
    
  • 暗黙のeval()は禁止。

    eslint: no-implied-eval

    js
    setTimeout("alert('Hello world')")                   // ✗ avoid
    setTimeout(function () { alert('Hello world') })     // ✓ ok
    
  • ネストされたブロック内に関数宣言は禁止。

    eslint: no-inner-declarations

    js
    if (authenticated) {
      function setAuthUser () {}    // ✗ avoid
    }
    
  • RegExpクラスのコンストラクタに無効な正規表現文字列は禁止。

    eslint: no-invalid-regexp

    js
    RegExp('[a-z')    // ✗ avoid
    RegExp('[a-z]')   // ✓ ok
    
  • イレギュラーな空白は禁止。

    eslint: no-irregular-whitespace

    js
    function myFunc () /*<NBSP>*/{}   // ✗ avoid
    
  • __iterator__は使用禁止。

    eslint: no-iterator

    js
    Foo.prototype.__iterator__ = function () {}   // ✗ avoid
    
  • スコープ変数と名前を共有するラベルは禁止。

    eslint: no-label-var

    js
    var score = 100
    function game () {
      score: while (true) {      // ✗ avoid
        score -= 10
        if (score > 0) continue score
        break
      }
    }
    
  • label文は禁止。

    eslint: no-labels

    js
    label:
      while (true) {
        break label     // ✗ avoid
      }
    
  • 不必要にネストされたブロックは禁止。

    eslint: no-lone-blocks

    js
    function myFunc () {
      {                   // ✗ avoid
        myOtherFunc()
      }
    }
    
    function myFunc () {
      myOtherFunc()       // ✓ ok
    }
    
  • インデントにスペースとタブを混ぜない。

    eslint: no-mixed-spaces-and-tabs

  • インデント以外に複数のスペースを使用しない。

    eslint: no-multi-spaces

    js
    const id =    1234    // ✗ avoid
    const id = 1234       // ✓ ok
    
  • 複数行の文字列は禁止。

    eslint: no-multi-str

    js
    const message = 'Hello \
                     world'     // ✗ avoid
    
  • オブジェクトを変数に代入しないnew演算子は禁止。

    eslint: no-new

    js
    new Character()                     // ✗ avoid
    const character = new Character()   // ✓ ok
    
  • Functionクラスのコンストラクタは使用禁止。

    eslint: no-new-func

    js
    var sum = new Function('a', 'b', 'return a + b')    // ✗ avoid
    
  • Objectクラスのコンストラクタは使用禁止。

    eslint: no-new-object

    js
    let config = new Object()   // ✗ avoid
    
  • new requireは使用禁止。

    eslint: no-new-require

    js
    const myModule = new require('my-module')    // ✗ avoid
    
  • Symbolクラスのコンストラクタは使用禁止。

    eslint: no-new-symbol

    js
    const foo = new Symbol('foo')   // ✗ avoid
    
  • プリミティブ型のラッパーインスタンスは使用禁止。

    eslint: no-new-wrappers

    js
    const message = new String('hello')   // ✗ avoid
    
  • 関数としてグローバルオブジェクトのプロパティを呼び出さない。

    eslint: no-obj-calls

    js
    const math = Math()   // ✗ avoid
    
  • 8進数リテラルは禁止。

    eslint: no-octal

    js
    const octal = 042         // ✗ avoid
    const decimal = 34        // ✓ ok
    const octalString = '042' // ✓ ok
    
  • 文字列リテラルに8進数エスケープシーケンスは禁止。

    eslint: no-octal-escape

    js
    const copyright = 'Copyright \251'  // ✗ avoid
    
  • __dirname__filenameは、文字列結合を避ける。

    eslint: no-path-concat

    js
    const pathToFile = __dirname + '/app.js'            // ✗ avoid
    const pathToFile = path.join(__dirname, 'app.js')   // ✓ ok
    
  • __proto__を使用しない。 代わりにgetPrototypeOfを使用する。

    eslint: no-proto

    js
    const foo = obj.__proto__               // ✗ avoid
    const foo = Object.getPrototypeOf(obj)  // ✓ ok
    
  • 変数を再宣言してはいけない。

    eslint: no-redeclare

    js
    let name = 'John'
    let name = 'Jane'     // ✗ avoid
    
    let name = 'John'
    name = 'Jane'         // ✓ ok
    
  • 正規表現リテラルに複数のスペースは禁止。

    eslint: no-regex-spaces

    js
    const regexp = /test   value/   // ✗ avoid
    
    const regexp = /test {3}value/  // ✓ ok
    const regexp = /test value/     // ✓ ok
    
  • return文における代入は括弧で囲まれていなければならない。

    eslint: no-return-assign

    js
    function sum (a, b) {
      return result = a + b     // ✗ avoid
    }
    
    function sum (a, b) {
      return (result = a + b)   // ✓ ok
    }
    
  • 変数を自身に代入しない。

    eslint: no-self-assign

    js
    name = name   // ✗ avoid
    
  • 変数を自身と比較しない。

    eslint: no-self-compare

    js
    if (score === score) {}   // ✗ avoid
    
  • カンマ演算子を使用しない。

    eslint: no-sequences

    js
    if (doSomething(), !!test) {}   // ✗ avoid
    
  • 制限付きの名前(訳注: restricted-name. strict mode の対象であるES5の予約語)を上書きして隠蔽するべきではない。

    eslint: no-shadow-restricted-names

    js
    let undefined = 'value'     // ✗ avoid
    
  • 疎配列は許容されない。

    eslint: no-sparse-arrays

    js
    let fruits = ['apple',, 'orange']       // ✗ avoid
    
  • タブの使用は推奨されない。

    eslint: no-tabs

  • 通常の文字列にテンプレートリテラルのプレースホルダーを含んではいけない。

    eslint: no-template-curly-in-string

    js
    const message = 'Hello ${name}'   // ✗ avoid
    const message = `Hello ${name}`   // ✓ ok
    
  • super()thisを使う前に呼び出さなければならない。

    eslint: no-this-before-super

    js
    class Dog extends Animal {
      constructor () {
        this.legs = 4     // ✗ avoid
        super()
      }
    }
    
  • Errorオブジェクトのみをスローしてください。

    eslint: no-throw-literal

    js
    throw 'error'               // ✗ avoid
    throw new Error('error')    // ✓ ok
    
  • 行末の空白はしないこと。

    eslint: no-trailing-spaces

  • undefinedでの初期化はしないこと。

    eslint: no-undef-init

    js
    let name = undefined    // ✗ avoid
    
    let name
    name = 'value'          // ✓ ok
    
  • 更新されないループ条件は禁止。

    eslint: no-unmodified-loop-condition

    js
    for (let i = 0; i < items.length; j++) {...}    // ✗ avoid
    for (let i = 0; i < items.length; i++) {...}    // ✓ ok
    
  • よりシンプルな書き方がある場合は、三項演算子は使用禁止。

    eslint: no-unneeded-ternary

    js
    let score = val ? val : 0     // ✗ avoid
    let score = val || 0          // ✓ ok
    
  • return文、throw文、continue文、break文の後に到達不能なコードは禁止。

    eslint: no-unreachable

    js
    function doSomething () {
      return true
      console.log('never called')     // ✗ avoid
    }
    
  • finallyブロックにフロー制御文は禁止。

    eslint: no-unsafe-finally

    js
    try {
      // ...
    } catch (e) {
      // ...
    } finally {
      return 42     // ✗ avoid
    }
    
  • 関係演算子の左オペランドを否定することは禁止。

    eslint: no-unsafe-negation

    js
    if (!key in obj) {}       // ✗ avoid
    if (!(key in obj)) {}     // ✓ ok
    
  • .call().apply()を不必要に使用しない。

    eslint: no-useless-call

    js
    sum.call(null, 1, 2, 3)   // ✗ avoid
    
  • オブジェクトの計算されたプロパティ名(Computed Property)を不必要に使用しない。

    eslint: no-useless-computed-key

    js
    const user = { ['name']: 'John Doe' }   // ✗ avoid
    const user = { name: 'John Doe' }       // ✓ ok
    
  • 不要なコンストラクタは禁止。

    eslint: no-useless-constructor

    js
    class Car {
      constructor () {      // ✗ avoid
      }
    }
    
  • エスケープを不必要に使用しない。

    eslint: no-useless-escape

    js
    let message = 'Hell\o'  // ✗ avoid
    
  • import、export、分割代入での、同じ名前へのリネームはしないこと。

    eslint: no-useless-rename

    js
    import { config as config } from './config'     // ✗ avoid
    import { config } from './config'               // ✓ ok
    
  • プロパティの前に空白は禁止。

    eslint: no-whitespace-before-property

    js
    user .name      // ✗ avoid
    user.name       // ✓ ok
    
  • with文は使用禁止。

    eslint: no-with

    js
    with (val) {...}    // ✗ avoid
    
  • オブジェクトのプロパティ間で、改行の一貫性を保つこと

    eslint: object-property-newline

    js
    const 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-blocks

    js
    if (user) {
                                // ✗ avoid
      const name = getName()
    
    }
    
    if (user) {
      const name = getName()    // ✓ ok
    }
    
  • スプレッド演算子とその式の間に空白は禁止。

    eslint: rest-spread-spacing

    js
    fn(... args)    // ✗ avoid
    fn(...args)     // ✓ ok
    
  • セミコロンの後にはスペースが必要。また、セミコロン前のスペースは不要

    eslint: semi-spacing

    js
    for (let i = 0 ;i < items.length ;i++) {...}    // ✗ avoid
    for (let i = 0; i < items.length; i++) {...}    // ✓ ok
    
  • ブロックの中括弧の前にはスペースが必要。

    eslint: space-before-blocks

    js
    if (admin){...}     // ✗ avoid
    if (admin) {...}    // ✓ ok
    
  • 括弧の内側にスペースは禁止。

    eslint: space-in-parens

    js
    getName( name )     // ✗ avoid
    getName(name)       // ✓ ok
    
  • 単項演算子の後にはスペースが必要。

    eslint: space-unary-ops

    js
    typeof!admin        // ✗ avoid
    typeof !admin        // ✓ ok
    
  • コメントの内側にスペースを入れること。

    eslint: spaced-comment

    js
    //comment           // ✗ avoid
    // comment          // ✓ ok
    
    /*comment*/         // ✗ avoid
    /* comment */       // ✓ ok
    
  • テンプレート文字列のプレースホルダーの内側にスペースは禁止。

    eslint: template-curly-spacing

    js
    const message = `Hello, ${ name }`    // ✗ avoid
    const message = `Hello, ${name}`      // ✓ ok
    
  • NaNのチェックにはisNaN()を使用する。

    eslint: use-isnan

    js
    if (price === NaN) { }      // ✗ avoid
    if (isNaN(price)) { }       // ✓ ok
    
  • typeofは有効な文字列と比較しなければならない。

    eslint: valid-typeof

    js
    typeof name === 'undefimed'     // ✗ avoid
    typeof name === 'undefined'     // ✓ ok
    
  • 即時実行関数式(IIFE)はラップしなければならない。

    eslint: wrap-iife

    js
    const getName = function () { }()     // ✗ avoid
    
    const getName = (function () { }())   // ✓ ok
    const getName = (function () { })()   // ✓ ok
    
  • yield*式の*は前後にスペースが必要。

    eslint: yield-star-spacing

    js
    yield* increment()    // ✗ avoid
    yield * increment()   // ✓ ok
    
  • ヨーダ記法を使用しない。

    eslint: yoda

    js
    if (42 === age) { }    // ✗ avoid
    if (age === 42) { }    // ✓ ok
    

セミコロン

  • セミコロンは不要。 (右記を参照のこと: 123

    eslint: semi

    js
    window.alert('hi')   // ✓ ok
    window.alert('hi');  // ✗ avoid
    
  • 決して([`(または下記の起こりうる可能性の低い一部の文字)で行を始めないでください。

    これはセミコロンを省略する際の唯一の問題点ですが、standardはこの潜在的な問題からあなたを保護します。

    (完全なリストは[(`+*/-,.ですが、これらのほとんどは実際のコードでは行頭には現れません。)

    eslint: no-unexpected-multiline

    js
    // ✓ ok
    ;(function () {
      window.alert('ok')
    }())
    
    // ✗ avoid
    (function () {
      window.alert('ok')
    }())
    
    js
    // ✓ ok
    ;[1, 2, 3].forEach(bar)
    
    // ✗ avoid
    [1, 2, 3].forEach(bar)
    
    js
    // ✓ ok
    ;`hello`.indexOf('o')
    
    // ✗ avoid
    `hello`.indexOf('o')
    

    注:もしあなたがこのようなコードをよく書くのであれば、あなたはあまりにも賢明な書き方をしようとしているのかもしれません。

    賢明なショートハンドは推奨されません。可能な限り明確で読みやすい表現を心がけてください。

    これのかわりに:

    js
    ;[1, 2, 3].forEach(bar)
    

    これが強く推奨されます。:

    js
    var nums = [1, 2, 3]
    nums.forEach(bar)
    

参考文書

参考ビデオ:

今日使用されている一般的なコードミニファイアー(圧縮ツール)はASTベースのミニフィケーションを使用しているので、セミコロンレスなJavaScriptを問題なく扱うことができます(JavaScriptではセミコロンは不要であるため)。

"An Open Letter to JavaScript Leaders Regarding Semicolons" からの抜粋:

[Relying on automatic semicolon insertion] is quite safe, and perfectly valid JS that every browser understands. Closure compiler, yuicompressor, packer, and jsmin all can properly minify it. There is no performance impact anywhere.

I am sorry that, instead of educating you, the leaders in this language community have given you lies and fear. That was shameful. I recommend learning how statements in JS are actually terminated (and in which cases they are not terminated), so that you can write code that you find beautiful.

In general, \n ends a statement unless:

  1. The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with . or ,.)
  2. The line is -- or ++ (in which case it will decrement/increment the next token.)
  3. It is a for(), while(), do, if(), or else, and there is no {
  4. The next line starts with [, (, +, *, /, -, ,, ., or some other binary operator that can only be found between two tokens in a single expression.

The first is pretty obvious. Even JSLint is ok with \n chars in JSON and parenthesized constructs, and with var statements that span multiple lines ending in ,.

The second is super weird. I’ve never seen a case (outside of these sorts of conversations) where you’d want to do write i\n++\nj, but, point of fact, that’s parsed as i; ++j, not i++; j.

The third is well understood, if generally despised. if (x)\ny() is equivalent to if (x) { y() }. The construct doesn’t end until it reaches either a block, or a statement.

; is a valid JavaScript statement, so if(x); is equivalent to if(x){} or, “If x, do nothing.” This is more commonly applied to loops where the loop check also is the update function. Unusual, but not unheard of.

The fourth is generally the fud-inducing “oh noes, you need semicolons!” case. But, as it turns out, it’s quite easy to prefix those lines with semicolons if you don’t mean them to be continuations of the previous line. For example, instead of this:

js
foo();
[1,2,3].forEach(bar);

you could do this:

js
foo()
;[1,2,3].forEach(bar)

The advantage is that the prefixes are easier to notice, once you are accustomed to never seeing lines starting with ( or [ without semis.