LoginSignup
1904

More than 1 year has passed since last update.

2021年に知っておきたいJavaScript最適化技術34選

Last updated at Posted at 2021-05-17

本記事は、Atit氏による「34 JavaScript Optimization Techniques to Know in 2021」(2021年1月3日公開)の和訳を、著者の許可を得て掲載しているものです。

2021年に知っておきたいJavaScript最適化技術34選

最新の省略テクニック、コツ、秘訣で、JavaScriptコードを最適化する。

開発者の生活というのは常に新しいことを学ぶことで、その変化についていくことは決して難しいことではありません。私は、フロントエンド開発者として知っておく必要のある省略形や機能など、JavaScriptのすべてのベストプラクティスを紹介して、2021年の生活をより快適にしたいと考えています。

Image for post

JavaScript開発に長く携わっている人でも、コードを追加しなくても問題解決できるような最新機能を知らないこともあるかもしれません。ここで紹介するものは、クリーンで最適化されたJavaScriptのコード記述にも、2021年のJavaScriptの面接準備にも役立ちます。

これは新しいシリーズで、2021年版のJavaScriptコーディングチートシートです。

1. 複数の条件を持つif

配列に複数の値を格納し、includesメソッドを使います。

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
   //logic
}

//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}

2. if true ... elseの省略形

if-else条件に大量のロジックがない場合は、とても短くできます。三項演算子を使うだけです。

// Longhand
let test: boolean;

if (x > 100) {
   test = true;
} else {
   test = false;
}

// Shorthand
let test = (x > 10) ? true : false;
//or we can use directly
let test = x > 10;

console.log(test);

ネストされた条件は、次のようにします。

let x = 300,
test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"

3. 変数宣言

共通の値または型を持つ2つの変数を宣言する場合、この省略形を使います。

//Longhand
let test1;
let test2 = 1;

//Shorthand
let test1, test2 = 1;

4. null/未定義/空の判定

新しい変数を作成する時、その値を参照している変数がnullまたはundefinedでないかを判定する、JavaScriptの優れた省略形です。

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
   let test2 = test1;
}

// Shorthand
let test2 = test1 || '';

5. null値の判定とデフォルト値の割り当て

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // output will be ""

6. 未定義値の判定とデフォルト値の割り当て

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // output will be ""

正常値の判定

let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // output: 'test'

(おまけ:これで前述の4、5、6でも??が使えます。)

null合体演算子

null合体演算子??は、左辺がnullまたは未定義の場合、右辺の値を返します。デフォルトでは、左辺の値を返します。

const test= null ?? 'default';
console.log(test);
// expected output: "default"const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0

7. 複数の変数への値の割り当て

複数の変数の処理で、各変数に異なる値を割り当てる時は、この省略形がとても便利です。

//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;

//Shorthand
let [test1, test2, test3] = [1, 2, 3];

8. 代入演算子の省略形

プログラミングでは、多くの算術演算子を扱います。これは、JavaScript変数への代入演算子の便利なテクニックです。

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;

// Shorthand
test1++;
test2--;
test3 *= 20;

9. ifによる存在確認の省略形

誰でも使っている一般的な省略形ですが、それでも言及する価値があります。

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)

// Shorthand //it will check empty string,null and undefined too
if (test1)

注:もしtest1に値があれば、ifループの後のロジックに入ります。この演算子は、主にnullまたはundefinedの確認に使われます。

10. 複数条件のAND (&&) 演算子

変数がtrueの時だけ関数を呼び出す場合は、&&演算子を使います。

//Longhand
if (test1) {
   callMethod();
}

//Shorthand
test1 && callMethod();

11. foreachループ

ループの一般的な省略形です。

// Longhand
for (var i = 0; i < testData.length; i++)

// Shorthand
for (let i in testData) or for (let i of testData)

各変数の配列

function testData(element, index, array) {
   console.log('test[' + index + '] = ' + element);
}

[11, 24, 32].forEach(testData);
// logs: test[0] = 11, test[1] = 24, test[2] = 32

12. 比較のreturn

比較はreturn文でも使えます。5行のコードが1行に減ります。

// Longhand
let test;

function checkReturn() {
   if (!(test === undefined)) {
      return test;
   } else {
      return callMe('test');
   }
}
var data = checkReturn();
console.log(data); //output test

function callMe(val) {
   console.log(val);
}

// Shorthand
function checkReturn() {
   return test || callMe('test');
}

13. アロー関数

例1

//Longhand
function add(a, b) {
   return a + b;
}

//Shorthand
const add = (a, b) => a + b;

例2

function callMe(name) {
   console.log('Hello', name);
}
callMe = name => console.log('Hello', name);

14. 短い関数の呼び出し

三項演算子を使います。

// Longhand
function test1() {
   console.log('test1');
};
function test2() {
   console.log('test2');
};

var test3 = 1;
if (test3 == 1) {
   test1();
} else {
   test2();
}

// Shorthand
(test3 === 1? test1:test2)();

15. switchの省略形

key-valueオブジェクトに条件を保存し、その条件に基づいて使用します。

// Longhand
switch (data) {
   case 1:
      test1();
   break;
   case 2:
      test2();
   break;
   case 3:
      test();
   break;
   // And so on...
}

// Shorthand
var data = {
   1: test1,
   2: test2,
   3: test
};

data[something] && data[something]();

16. 暗黙の戻り

アロー関数を使えば、return文なしで直接値を返します。

//longhand
function calculate(diameter) {
   return Math.PI * diameter
}

//shorthand
calculate = diameter => (
   Math.PI * diameter;
)

17. 10進数ベース指数

// Longhand
for (var i = 0; i < 10000; i++) { ... }

// Shorthand
for (var i = 0; i < 1e4; i++) {

18. パラメータのデフォルト値

//Longhand
function add(test1, test2) {
   if (test1 === undefined)
      test1 = 1;
   if (test2 === undefined)
      test2 = 2;
   return test1 + test2;
}

//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);

add() //output: 3

19. スプレッド演算子

//longhand
// joining arrays using concat
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);

//shorthand
// joining arrays
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]

スプレッド演算子は、クローン作成にも使えます。

//longhand
// cloning arrays
const test1 = [1, 2, 3];
const test2 = test1.slice()

//shorthand
// cloning arrays
const test1 = [1, 2, 3];
const test2 = [...test1];

20. テンプレートリテラル

+で複数の変数を1つの文字列に連結するのが面倒な場合、この省略形で楽になります。

//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'

//shorthand
const welcome = `Hi ${test1} ${test2}`;

21. 複数行の文字列の省略形

コードで複数行の文字列を処理する場合、この関数を使えます。

//longhand
const data = 'abc abc abc abc abc abc\n\t'
   + 'test test,test test test test\n\t'

//shorthand
const data = `abc abc abc abc abc abc
   test test,test test test test`

22. オブジェクトプロパティの割り当て

let test1 = 'a';
let test2 = 'b';

//Longhand
let obj = {test1: test1, test2: test2};

//Shorthand
let obj = {test1, test2};

23. 文字列の数値への変換

//Longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');

//Shorthand
let test1 = +'123';
let test2 = +'12.3';

24. 分割代入の省略形

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;

//shorthand
const { test1, test2, test3 } = this.data;

25. Array.find

オブジェクトの配列で、オブジェクトのプロパティに基づいて特定のオブジェクトを探す場合、findメソッドはとても便利です。

const data = [{
      type: 'test1',
      name: 'abc'
   },
   {
      type: 'test2',
      name: 'cde'
   },
   {
      type: 'test1',
      name: 'fgh'
   },
]

function findtest1(name) {
   for (let i = 0; i < data.length; ++i) {
      if (data[i].type === 'test1' && data[i].name === name) {
         return data[i];
      }
   }
}

//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }

26. 検索条件の省略形

型をチェックするコードで、型に基づいて異なるメソッドを呼び出す場合、複数のelse ifか、switchの選択肢がありますが、それより優れた省略形があります。

// Longhand
if (type === 'test1') {
   test1();
}
else if (type === 'test2') {
   test2();
}
else if (type === 'test3') {
   test3();
}
else if (type === 'test4') {
   test4();
} else {
   throw new Error('Invalid value ' + type);
}

// Shorthand
var types = {
   test1: test1,
   test2: test2,
   test3: test3,
   test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();

27. ビット単位演算子によるIndexOfの省略形

配列をループして特定の値を探す場合、indexOf()メソッドを使います。それより優れた方法の例を見てみましょう。

//longhand
if(arr.indexOf(item) > -1) { // item found }
if(arr.indexOf(item) === -1) { // item not found }

//shorthand
if(~arr.indexOf(item)) { // item found }
if(!~arr.indexOf(item)) { // item not found }

ビット単位演算子~は、-1以外の値に真の値を返します。否定は簡単で、!~とするだけです。include()関数も使えます。

if (arr.includes(item)) {
// true if the item found
}

28. Object.entries()

この機能は、オブジェクトをオブジェクト配列に変換するのに便利です。

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);

/** Output:
[ [ 'test1', 'abc' ],
  [ 'test2', 'cde' ],
  [ 'test3', 'efg' ]
]
**/

29. Object.values()

これもES8で導入された新機能で、Object.entries()と似ていますが、キーがありません。

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);

/** Output:
[ 'abc', 'cde']
**/

30. ダブルビット単位の省略形

(ダブルビット否定演算子のアプローチは、32ビット整数に対してのみ有効です。)

// Longhand
Math.floor(1.9) === 1 // true

// Shorthand
~~1.9 === 1 // true

31. 文字列の繰り返し

同じ文字を何回も繰り返す場合、forループで同じループに追加できますが、省略形があります。

//longhand
let test = '';
for(let i = 0; i < 5; i ++) {
   test += 'test ';
}
console.log(str); // test test test test test

//shorthand
'test '.repeat(5);

32. 配列の最大値と最小値を取得

const arr = [1, 2, 3];
Math.max(...arr); // 3
Math.min(...arr); // 1

33. 文字列から文字を取得

let str = 'abc';

//Longhand
str.charAt(2); // c

//Shorthand
str[2]; // c

注:配列のインデックスが分かっている場合、文字の代わりに直接インデックスが使えます。インデックスが分からない場合、未定義のエラーが発生します。

34. べき関数の省略形

Mathの指数べき関数の省略形です。

//longhand
Math.pow(2,3); // 8

//shorthand
2**3 // 8

おわりに

最新のJavaScript技術でコードを最適化する34の方法でした。

記事を楽しんでいただけましたか?私達のYouTubeチャンネルに登録して、関連コンテンツをもっとご覧ください!

翻訳協力

この記事は以下の方々のご協力により公開する事ができました。改めて感謝致します。

Original Author: Atit
Original Article: 34 JavaScript Optimization Techniques to Know in 2021
Thank you for letting us share your knowledge!

選定担当: @gracen
翻訳担当: @gracen
監査担当: -
公開担当: @gracen

ご意見・ご感想をお待ちしております

今回の記事はいかがでしたか?
・こういう記事が読みたい
・こういうところが良かった
・こうした方が良いのではないか
などなど、率直なご意見を募集しております。
頂いたお声は、今後の記事の質向上に役立たせて頂きますので、お気軽に
コメント欄にてご投稿ください。Twitterでもご意見を受け付けております。
皆様のメッセージをお待ちしております。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1904