Movatterモバイル変換


[0]ホーム

URL:


LoginSignup
1653

Go to list of users who liked

1891

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated atPosted 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メソッドを使います。

//longhandif(x==='abc'||x==='def'||x==='ghi'||x==='jkl'){//logic}//shorthandif(['abc','def','ghi','jkl'].includes(x)){//logic}

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

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

// Longhandlettest:boolean;if(x>100){test=true;}else{test=false;}// Shorthandlettest=(x>10)?true:false;//or we can use directlylettest=x>10;console.log(test);

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

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

3. 変数宣言

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

//Longhandlettest1;lettest2=1;//Shorthandlettest1,test2=1;

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

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

// Longhandif(test1!==null||test1!==undefined||test1!==''){lettest2=test1;}// Shorthandlettest2=test1||'';

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

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

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

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

正常値の判定

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

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

null合体演算子

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

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

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

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

//Longhandlettest1,test2,test3;test1=1;test2=2;test3=3;//Shorthandlet[test1,test2,test3]=[1,2,3];

8. 代入演算子の省略形

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

// Longhandtest1=test1+1;test2=test2-1;test3=test3*20;// Shorthandtest1++;test2--;test3*=20;

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

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

// Longhandif(test1===true)orif(test1!=="")orif(test1!==null)// Shorthand //it will check empty string,null and undefined tooif(test1)

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

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

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

//Longhandif(test1){callMethod();}//Shorthandtest1&&callMethod();

11. foreachループ

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

// Longhandfor(vari=0;i<testData.length;i++)// Shorthandfor(letiintestData)orfor(letioftestData)

各変数の配列

functiontestData(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行に減ります。

// Longhandlettest;functioncheckReturn(){if(!(test===undefined)){returntest;}else{returncallMe('test');}}vardata=checkReturn();console.log(data);//output testfunctioncallMe(val){console.log(val);}// ShorthandfunctioncheckReturn(){returntest||callMe('test');}

13. アロー関数

例1

//Longhandfunctionadd(a,b){returna+b;}//Shorthandconstadd=(a,b)=>a+b;

例2

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

14. 短い関数の呼び出し

三項演算子を使います。

// Longhandfunctiontest1(){console.log('test1');};functiontest2(){console.log('test2');};vartest3=1;if(test3==1){test1();}else{test2();}// Shorthand(test3===1?test1:test2)();

15. switchの省略形

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

// Longhandswitch(data){case1:test1();break;case2:test2();break;case3:test();break;// And so on...}// Shorthandvardata={1:test1,2:test2,3:test};data[something]&&data[something]();

16. 暗黙の戻り

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

//longhandfunctioncalculate(diameter){returnMath.PI*diameter}//shorthandcalculate=diameter=>(Math.PI*diameter;)

17. 10進数ベース指数

// Longhandfor(vari=0;i<10000;i++){...}// Shorthandfor(vari=0;i<1e4;i++){

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

//Longhandfunctionadd(test1,test2){if(test1===undefined)test1=1;if(test2===undefined)test2=2;returntest1+test2;}//shorthandadd=(test1=1,test2=2)=>(test1+test2);add()//output: 3

19. スプレッド演算子

//longhand// joining arrays using concatconstdata=[1,2,3];consttest=[4,5,6].concat(data);//shorthand// joining arraysconstdata=[1,2,3];consttest=[4,5,6,...data];console.log(test);// [ 4, 5, 6, 1, 2, 3]

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

//longhand// cloning arraysconsttest1=[1,2,3];consttest2=test1.slice()//shorthand// cloning arraysconsttest1=[1,2,3];consttest2=[...test1];

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

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

//longhandconstwelcome='Hi'+test1+''+test2+'.'//shorthandconstwelcome=`Hi${test1}${test2}`;

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

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

//longhandconstdata='abc abc abc abc abc abc\n\t'+'test test,test test test test\n\t'//shorthandconstdata=`abc abc abc abc abc abc   test test,test test test test`

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

lettest1='a';lettest2='b';//Longhandletobj={test1:test1,test2:test2};//Shorthandletobj={test1,test2};

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

//Longhandlettest1=parseInt('123');lettest2=parseFloat('12.3');//Shorthandlettest1=+'123';lettest2=+'12.3';

24. 分割代入の省略形

//longhandconsttest1=this.data.test1;consttest2=this.data.test2;consttest2=this.data.test3;//shorthandconst{test1,test2,test3}=this.data;

25. Array.find

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

constdata=[{type:'test1',name:'abc'},{type:'test2',name:'cde'},{type:'test1',name:'fgh'},]functionfindtest1(name){for(leti=0;i<data.length;++i){if(data[i].type==='test1'&&data[i].name===name){returndata[i];}}}//ShorthandfilteredData=data.find(data=>data.type==='test1'&&data.name==='fgh');console.log(filteredData);// { type: 'test1', name: 'fgh' }

26. 検索条件の省略形

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

// Longhandif(type==='test1'){test1();}elseif(type==='test2'){test2();}elseif(type==='test3'){test3();}elseif(type==='test4'){test4();}else{thrownewError('Invalid value'+type);}// Shorthandvartypes={test1:test1,test2:test2,test3:test3,test4:test4};varfunc=types[type];(!func)&&thrownewError('Invalid value'+type);func();

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

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

//longhandif(arr.indexOf(item)>-1){// item found }if(arr.indexOf(item)===-1){// item not found }//shorthandif(~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()

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

constdata={test1:'abc',test2:'cde',test3:'efg'};constarr=Object.entries(data);console.log(arr);/** Output:[ [ 'test1', 'abc' ],  [ 'test2', 'cde' ],  [ 'test3', 'efg' ]]**/

29. Object.values()

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

constdata={test1:'abc',test2:'cde'};constarr=Object.values(data);console.log(arr);/** Output:[ 'abc', 'cde']**/

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

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

// LonghandMath.floor(1.9)===1// true// Shorthand~~1.9===1// true

31. 文字列の繰り返し

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

//longhandlettest='';for(leti=0;i<5;i++){test+='test';}console.log(str);// test test test test test//shorthand'test'.repeat(5);

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

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

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

letstr='abc';//Longhandstr.charAt(2);// c//Shorthandstr[2];// c

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

34. べき関数の省略形

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

//longhandMath.pow(2,3);// 8//shorthand2**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でもご意見を受け付けております。
皆様のメッセージをお待ちしております。

1653

Go to list of users who liked

1891
19

Go to list of comments

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
1653

Go to list of users who liked

1891

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?


[8]ページ先頭

©2009-2025 Movatter.jp