- 開発
READ MORE
AirbnbによるJavaScriptスタイルガイドです。
MITライセンスに基いて翻訳・公開いたします。
原文にはありませんが、利便性のため項目ごとに目安となる分類を【】で示しました。
なお、Translationに日本語を含む各国の既存訳へのリンク一覧があります。
メモ: 本ガイドではBabelの利用を前提とします。また、babel-preset-airbnbあるいは同等のライブラリが必要です。他に、airbnb-browser-shimsまたは同等のライブラリでshims/polyfillsをアプリにインストールしていることも前提とします。
string
number
boolean
null
undefined
const foo = 1;
let bar = foo;
bar = 9;
console.log(foo, bar); // => 1, 9
object
array
function
const foo = [1, 2];
const bar = foo;
bar[0] = 9;
console.log(foo[0], bar[0]); // => 9, 9
const
を使い、var
は避けること。prefer-const
, no-const-assign
理由:
const
を使うことで、参照への再代入を防止できる。参照への再代入はバグを誘発し、コードを読みづらくする。
// Bad: 定数をvarで宣言している
var a = 1;
var b = 2;
// Good: 定数をconstで宣言している
const a = 1;
const b = 2;
var
ではなくlet
を使うこと。no-var
disallowVar
理由:
let
はブロックスコープであり、var
などのような関数スコープではない。
// Bad
var count = 1;
if (true) {
count += 1;
}
// Good: letを使うべき
let count = 1;
if (true) {
count += 1;
}
let
とconst
はどちらもブロックスコープである点に注意すること。// constとletはどちらもそれらが宣言されたブロック内でのみ有効
{
let a = 1;
const b = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError
new
を使わないこと)。no-new-object
// Bad
const item = new Object();
// Good
const item = {};
理由: computedプロパティ名を使うと、オブジェクトの全プロパティを1箇所で定義できる。
function getKey(k) {
return `a key named ${k}`;
}
// Bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;
// Good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};
object-shorthand
requireEnhancedObjectLiterals
// Bad
const atom = {
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// Good: 「addValue(value)」ショートハンド形式にする
const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};
object-shorthand
requireEnhancedObjectLiterals
理由: 短くて書きやすく、内容を端的に表せる。
const lukeSkywalker = 'Luke Skywalker';
// Bad
const obj = {
lukeSkywalker: lukeSkywalker,
};
// Good
const obj = {
lukeSkywalker,
};
理由: ショートハンド形式のプロパティであることをわかりやすくするため。
const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
// Bad
const obj = {
episodeOne: 1,
twoJediWalkIntoACantina: 2,
lukeSkywalker,
episodeThree: 3,
mayTheFourth: 4,
anakinSkywalker,
};
// Good
const obj = {
lukeSkywalker,
anakinSkywalker,
episodeOne: 1,
twoJediWalkIntoACantina: 2,
episodeThree: 3,
mayTheFourth: 4,
};
quote-props
disallowQuotedKeysInObjects
理由: 主観的にはこの方が一般に読みやすいと考えられる。さらにシンタックスハイライトにもよい影響があり、さまざまなJSエンジンで最適化が効きやすくなる。
// Bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};
// Good: 'data-blah'だけ引用符で囲む
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};
Object.prototype
のメソッド(hasOwnProperty
、propertyIsEnumerable
、isPrototypeOf
など)を(.prototype
を介さずに)直接呼んではならない。理由: これらのメソッドは、そのオブジェクトのプロパティによって隠蔽される可能性がある。
{ hasOwnProperty: false }
の場合もあれば、オブジェクトが実際にはnullオブジェクト(Object.create(null)
)のこともある。
// Bad
console.log(object.hasOwnProperty(key));
// Good
console.log(Object.prototype.hasOwnProperty.call(object, key));
// ベスト
const has = Object.prototype.hasOwnProperty; // 探索はモジュールスコープ内で1度キャッシュされる。
/* 以下でもよい */
import has from 'has';
// ...
console.log(has.call(object, key));
Object.assign
を使わないこと。...
の利用が望ましい。...
演算子で受けること。// 非常に悪い
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // `original`が変更されてしまう! ಠ_ಠ
delete copy.a; // これも`original`が消される
// Bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 });
// copy => { a: 1, b: 2, c: 3 }
// Good
const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 };
// copy => { a: 1, b: 2, c: 3 }
const { a, ...noA } = copy;
// noA => { b: 2, c: 3 }
no-array-constructor
// Bad
const items = new Array();
// Good
const items = [];
const someStack = [];
// Bad
someStack[someStack.length] = 'abracadabra';
// Good
someStack.push('abracadabra');
...
を使うこと。// Bad
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i += 1) {
itemsCopy[i] = items[i];
}
// Good
const itemsCopy = [...items];
const foo = document.querySelectorAll('.foo');
const nodes = Array.from(foo);
return
文を使うこと。ただし、関数の内容が1文だけで、かつ副作用のない式を返す場合は8.2に基いてreturn
を省略してもよい。array-callback-return
// Good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
// Good
[1, 2, 3].map(x => x + 1);
// Bad
const flat = {};
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
const flatten = memo.concat(item);
flat[index] = flatten;
});
// Good
const flat = {};
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
const flatten = memo.concat(item);
flat[index] = flatten;
return flatten;
});
// Bad
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
} else {
return false;
}
});
// Good
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
}
return false;
});
[
の直後と閉じ角かっこ]
の直前を改行すること。// Bad
const arr = [
[0, 1], [2, 3], [4, 5],
];
const objectInArray = [{
id: 1,
}, {
id: 2,
}];
const numberInArray = [
1, 2,
];
// Good
const arr = [[0, 1], [2, 3], [4, 5]];
const objectInArray = [
{
id: 1,
},
{
id: 2,
},
];
const numberInArray = [
1,
2,
];
理由: プロパティの一時的な参照が作成されずに済むため。
// Bad
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
return `${firstName} ${lastName}`;
}
// Good
function getFullName(user) {
const { firstName, lastName } = user;
return `${firstName} ${lastName}`;
}
// ベスト
function getFullName({ firstName, lastName }) {
return `${firstName} ${lastName}`;
}
const arr = [1, 2, 3, 4];
// Bad
const first = arr[0];
const second = arr[1];
// Good
const [first, second] = arr;
理由: 今後プロパティを追加したり順序を変更したりしても呼び出し側に影響を与えずに済むため。
// Bad
function processInput(input) {
// この後えらいことになる
return [left, right, top, bottom];
}
// 呼び出し元は戻り値の順序を常に気にしなければならない
const [left, __, top] = processInput(input);
// Good
function processInput(input) {
// この後うれしいことが起きる
return { left, right, top, bottom };
}
// 呼び出し側は欲しいデータだけを使えばよい
const { left, top } = processInput(input);
' '
で囲むこと。quotes
validateQuoteMarks
// Bad
const name = "Capt. Janeway";
// Bad - テンプレートリテラルは式展開か改行を含む場合に使うべき
const name = `Capt. Janeway`;
// Good
const name = 'Capt. Janeway';
理由: 分割された文字列は扱いづらく、コードの検索性も落ちる。
// Bad
const errorMessage = 'このウルトラスーパー長いエラーメッセージがスローされたのは\
バットマンのせい。バットマンがそんなことをする理由をいくら考えたところでさっぱり\
先に進まない。';
// Bad
const errorMessage = 'このウルトラスーパー長いエラーメッセージがスローされたのは' +
'バットマンのせい。バットマンがそんなことをする理由をいくら考えたところでさっぱり' +
'先に進まない。';
// Good
const errorMessage = 'このウルトラスーパー長いエラーメッセージがスローされたのはバットマンのせい。バットマンがそんなことをする理由をいくら考えたところでさっぱり先に進まない。';
+
の文字列結合ではなく、テンプレート文字列を使うこと。prefer-template
template-curly-spacing
requireTemplateStrings
理由: テンプレート文字列は読みやすく、改行や文字列の式展開(interpolation)を正しく使える簡潔な文法であるため。
// Bad
function sayHi(name) {
return 'How are you, ' + name + '?';
}
// Bad
function sayHi(name) {
return ['How are you, ', name, '?'].join();
}
// Bad
function sayHi(name) {
return `How are you, ${ name }?`;
}
// Good: ${name}にはスペースを含めないこと
function sayHi(name) {
return `How are you, ${name}?`;
}
eval()
は決して文字列に対して使用してはならない。eval()
は無数の脆弱性を引き起こす。no-eval
\
でエスケープしないこと。no-useless-escape
理由: バックスラッシュ
\
は可読性を損なうため、本当に必要な場合にのみ使うこと。
// Bad
const foo = '\'this\' \i\s \"quoted\"';
// Good
const foo = '\'this\' is "quoted"';
const foo = `my name is '${name}'`;
func-style
disallowFunctionDeclarations
理由: 関数宣言は巻き上げられる(ホイスティング:hoisting)ため、ファイル内でその関数宣言の定義より上の位置から簡単に(あまりに簡単に)参照できてしまい、可読性もメンテナンス性も損なわれる。ある関数定義が、ファイルの他の部分をすべて理解しなければならないほど巨大で複雑になっているのであれば、そろそろ関数を独自のモジュールに切り出してもよいだろう。その際、式には必ず名前をつけること。無名関数を使うとエラーのコールスタックで問題を特定するのが困難になるかもしれない(議論 )。
// Bad: 関数宣言
function foo() {
// ...
}
// Bad: 無名関数
const foo = function () {
// ...
};
// Good: 名前付き関数式
const foo = function bar() {
// ...
};
( )
で囲むこと。wrap-iife
requireParenthesesAroundIIFE
理由: 即時関数式は単一のユニットであり、即時関数式とその呼出の丸かっこ
()
の両方を丸かっこ()
で囲むことで明確に表現できるようになる。ただし、あらゆる場所でモジュールが使われているような世界では、即時関数式が必要になることはほぼまったくありえない。
// 即時関数式(IIFE)
(function () {
console.log('インターネットへようこそ。フォローしてね。');
}());
if
やwhile
など)の中では決して関数宣言を行ってはならない。代わりに関数を変数に代入すること。ブラウザではそのようなコードでも動いてしまうが、コードはまったく違う形で解釈され、痛い目を見ることになる。no-loop-func
block
を文(statement)のリストと定義している。そして関数宣言は文ではない( ECMA-262の注記 を参照)。// Bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// Good
let test;
if (currentUser) {
test = () => {
console.log('Yup.');
};
}
arguments
という名前をつけてはならない。もし使うと、あらゆる関数スコープで与えられるarguments
オブジェクトが隠蔽されてしまう。// Bad
function foo(name, options, arguments) {
// ...
}
// Good
function foo(name, options, args) {
// ...
}
arguments
は決して使ってはならない。代わりに...
記法を使うこと。prefer-rest-params
理由:
...
を使うことで、どの引数を取得したいかが明確になる。さらに...
記法の引数は本物の配列である。arguments
のような配列もどきではない。
// Bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
// Good
function concatenateAll(...args) {
return args.join('');
}
// 非常に悪い
function handleThings(opts) {
// 関数でこのように引数を変更するべきではない!
// さらなる副作用: optsがfalsyの場合、必要なものがそのオブジェクトに
// 運よく設定されるかもしれないが、微妙なバグの原因になるかもしれない
opts = opts || {};
// ...
}
// これでも悪い
function handleThings(opts) {
if (opts === void 0) {
opts = {};
}
// ...
}
// Good
function handleThings(opts = {}) {
// ...
}
理由: 動作の理解で混乱を招く。
var b = 1;
// Bad
function count(a = b++) {
console.log(a);
}
count(); // 1
count(); // 2
count(3); // 3
count(); // 3
// Bad
function handleThings(opts = {}, name) {
// ...
}
// Good
function handleThings(name, opts = {}) {
// ...
}
no-new-func
理由: 関数コンストラクタを使うと文字列が
eval()
と似た方法で評価され、脆弱性が発生する。
// Bad
var add = new Function('a', 'b', 'return a + b');
// still bad
var subtract = Function('a', 'b', 'return a - b');
理由: スタイル統一のため。名前の追加や削除の際にこのスペースを増やしたり減らしたりすべきではない。
// Bad
const f = function(){};
const g = function (){};
const h = function() {};
// Good
const x = function () {};
const y = function a() {};
no-param-reassign
理由: パラメータとして渡されたオブジェクトを改変すると、呼び出し元で意図に反して変数の副作用が発生する可能性がある。
// Bad
function f1(obj) {
obj.key = 1;
}
// Good
function f2(obj) {
const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
}
no-param-reassign
理由: パラメータに再代入すると、特に
arguments
オブジェクトにアクセスするする場合に思わぬ挙動が発生する可能性がある。さらに、特にV8エンジンで最適化に問題が発生する可能性もある。
// Bad
function f1(a) {
a = 1;
// ...
}
function f2(a) {
if (!a) { a = 1; }
// ...
}
// Good
function f3(a) {
const b = a || 1;
// ...
}
function f4(a = 1) {
// ...
}
...
が望ましい。prefer-spread
理由:
...
の方が簡潔であり、コンテキストを与える必要がない。apply
を使うと(意味のない)new
が簡単にはできなくなる。
// Bad
const x = [1, 2, 3, 4, 5];
console.log.apply(console, x);
// Good
const x = [1, 2, 3, 4, 5];
console.log(...x);
// Bad
new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));
// Good
new Date(...[2016, 8, 5]);
// Bad
function foo(bar,
baz,
quux) {
// ...
}
// Good
function foo(
bar,
baz,
quux,
) {
// ...
}
// Bad
console.log(foo,
bar,
baz);
// Good
console.log(
foo,
bar,
baz,
);
prefer-arrow-callback
, arrow-spacing
requireArrowFunctions
理由: アロー関数を使うと、
this
のコンテキストで実行される関数が与えられる。これは多くの場合において適切であり、文法も簡潔になる。使わない場合の理由: 関数がかなり複雑な場合は、ロジックを独自の関数宣言に切り出すことを検討すること。
// Bad
[1, 2, 3].map(function (x) {
const y = x + 1;
return x * y;
});
// Good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
{}
とreturn
を省略するか、波かっこ {}
とreturn
を明示的に書くか、どちらかにする。arrow-parens
, arrow-body-style
disallowParenthesesAroundArrowParam
, requireShorthandArrowFunctions
理由: シンタックスシュガーであり、複数の関数を連鎖したときに読みやすくなる。
// Bad
[1, 2, 3].map(number => {
const nextNumber = number + 1;
`A string containing the ${nextNumber}.`;
});
// Good
[1, 2, 3].map(number => `A string containing the ${number}.`);
// Good
[1, 2, 3].map((number) => {
const nextNumber = number + 1;
return `A string containing the ${nextNumber}.`;
});
// Good
[1, 2, 3].map((number, index) => ({
[index]: number,
}));
// 副作用ありの場合のreturnの省略
function foo(callback) {
const val = callback();
if (val === true) {
// コールバックがtrueの場合に何かする
}
}
let bool = false;
// Bad
foo(() => bool = true);
// Good
foo(() => {
bool = true;
});
( )
で囲んで読みやすくする。理由: 関数の開始と終了がわかりやすくなる。
// Bad
['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
httpMagicObjectWithAVeryLongName,
httpMethod,
)
);
// Good
['get', 'post', 'put'].map(httpMethod => (
Object.prototype.hasOwnProperty.call(
httpMagicObjectWithAVeryLongName,
httpMethod,
)
));
{ }
を使わない関数では、引数の丸かっこ( )
を省略するか、読みやすさと一貫性のために引数を常に丸かっこ( )
で囲むか、どちらかにする。( )
で囲むスタイルも許容される。eslintでは“always” オプションをオンにし、jslintの場合はdisallowParenthesesAroundArrowParam
をすることで設定できる。arrow-parens
disallowParenthesesAroundArrowParam
理由: 可読性の向上。
// Bad
[1, 2, 3].map((x) => x * x);
// Good
[1, 2, 3].map(x => x * x);
// Good
[1, 2, 3].map(number => (
`${number}を含むとても長い文字列。あんまり長いので.map行で場所を取りたくない!`
));
// Bad
[1, 2, 3].map(x => {
const y = x + 1;
return x * y;
});
// Good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
<=
、>=
)と紛らわしい場合はアロー関数記法(=>
)の利用を避ける。no-confusing-arrow
// Bad
const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;
// Bad
const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;
// Good
const itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);
// Good
const itemHeight = (item) => {
const { height, largeSize, smallSize } = item;
return height > 256 ? largeSize : smallSize;
};