10 の JavaScript クリーン コード例

JavaScript クリーン コードは、読みやすく、保守しやすく、効率的な JavaScript コードを作成するために使用できる一連の原則と実践方法です。クリーンなコードを記述することは、他の開発者がコードを理解し、変更しやすくなり、アプリケーションのパフォーマンスの向上にも役立つため、重要です。

このチュートリアルでは、より読みやすく、保守しやすく、効率的なコードを作成するのに役立つ 10 個の JavaScript のクリーンなコード例を学びます。このチュートリアルでは、関数、変数、オブジェクト、ループなどのさまざまなトピックを取り上げます。

1. 三項演算子を使用して条件付きで同じものに値を代入します。

a > b ? foo = 'apple' : foo = 'ball'; 

✔️  
foo = a > b ? 'apple' : 'ball';

2. 特定のオブジェクトのプロパティに条件付きで同じ値を割り当てます。

c > d ? a.foo = 'apple' : a.bar = 'apple';

✔️  
a = { [c > d ? 'foo' : 'bar']: 'apple' };

3. 複数の変数のエクスポート

export const foo;
export const bar;
export const kip;

✔️ 
export const foo, bar, kip;

4. オブジェクトのプロパティから変数を宣言して代入します。

const a = foo.x, b = foo.y;

✔️
const { ['x']: a, ['y']: b } = foo;

5. 配列インデックスからの変数の宣言と代入。

let a = foo[0], b = foo[1];

✔️
let [a, b] = foo;

6. DOM から複数の要素を取得します。

const a = document.getElementById('a'),
b = document.getElementById('b'),
c = document.getElementById('c');
d = document.getElementById('d');

✔️
const elements = {};
['a', 'b', 'c', 'd'].forEach(item => elements = { 
  ...elements, 
  [item]: document.getElementById(item) 
});
const { a, b, c, d } = elements;

/*
For this to work your elements ID's must be 
able to be valid Javascript variable names
and the names of the variables in which you store
your elements have to match with that elements' ID.
This is good for naming consistency & accesibility.
*/

7. 単純な条件には論理演算子を使用します。

if (foo) {
  doSomething();
}

✔️
foo && doSomething();

8. パラメータを条件付きで渡します。

if(!foo){
  foo = 'apple';
}
bar(foo, kip);

✔️
bar(foo || 'apple', kip);

9. たくさんの 0 を扱う。

const SALARY = 150000000,
TAX = 15000000;

✔️
const SALARY = 15e7,
TAX = 15e6;

10. 複数の変数に同じものを代入する。

a = d;
b = d;
c = d;

✔️
a = b = c = d;

コーディングを楽しんでください!!!

1.00 GEEK