y_megane.log

日々の勉強や改善ネタの備忘。

javascriptコーディングスタイルの主要どころ

概要

セミコロンは必要なのか?
文字列はシングルクオートなのかダブルなのか?
命名規約は?
というjavascriptド素人(私)の疑問をスッキリさせるため、主要なコーディングまとめ。

結論

2020年1月時点ではAirbnbのコーディングスタイルが一番使われているらしい。
一通り目を通したが、素人なりに違和感なく読めて納得した上で使えそうな規約という印象。 本質ではないが規約とともにその根拠やサンプルコードがしっかり書かれているのもありがたい。

「とりあえず従おう」だけでなく、規約を読みこむことでjavaascriptコーディングの基本的なプラクティスが学べる。書籍でいうリーダブルコードやEffectiveJavaの軽量版のような感覚。

主流であること、学習コンテンツ的に役立ったことから、ひとまずAirbnb規約に従うことにする。

主要な規約

まとめ・比較系の記事

10 Best JavaScript Style Guides Including airbnb & Idiomatic

上のサイトによると

  • airbnbの規約が最もポピュラー
  • JavaScriptに対する最も合理的なアプローチ
  • 変数や関数、テストなど全領域をカバーしていることが利点

Airbnb規約抜粋

JavaScript初学者の私の迷いが晴れた、理解が深まったと感じた規約だけごく一部抜粋。
和訳があるのは大変ありがたいが、一部の訳が怪しいので一応英語版がおすすめ。

  • 4.2 Use Array#push instead of direct assignment to add items to an array
  • 4.3 Use array spreads ... to copy arrays.
  • 4.4 To convert an iterable object to an array, use spreads ... instead of Array.from.
  • 4.5 Use Array.from for converting an array-like object to an array.
  • 6.1 Use single quotes '' for strings.
  • 6.2 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation
  • 6.3 When programmatically building up strings, use template strings instead of concatenation.
  • 7.1 Use named function expressions instead of function declarations.
  • 7.7 Use default parameter syntax rather than mutating function arguments.
  • 7.11 Spacing in a function signature.
  • 7.14 Prefer the use of the spread operator ... to call variadic functions.
  • 13.7 Avoid linebreaks before or after = in an assignment. If your assignment violates max-len, surround the value in parens.
  • 15.1 Use === and !== over == and !=.
  • 17.1 In case your control statement (if, while etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line.
  • 18.5 Use // FIXME: to annotate problems.
  • 18.6 Use // TODO: to annotate solutions to problems.
  • 19.1 Use soft tabs (space character) set to 2 spaces.
  • 19.2 Place 1 space before the leading brace.
  • 19.3 Place 1 space before the opening parenthesis in control statements (if, while etc.). Place no space between the argument list and the function name in function calls and declarations.
  • 19.7 Leave a blank line after blocks and before the next statement.
  • 19.11 Add spaces inside curly braces.
  • 20.1 Leading commas: Nope.
  • 20.2 Additional trailing comma: Yup.