JavaScriptのショートハンド特集

JavaScriptのショートハンド特集パート1
JavaScriptのショートハンドコードをまとめていきたいと思います。
早速面白そうな記事を見つけたので読んでいきたい。

1. 複数の OR(||) 条件を持つ if 文記述の省略
carの値をチェックするif文を書くと、OR演算子使うことになる。
ただ、この場合だと複数の値を比較したい場合に可読性が落ちてしまう。
if (car === 'audi' || car === 'BMW' || car === 'Tesla') {
//code
}
配列に確認したい値を格納して、includes()
メソッドを用いる。
if (['audi', 'BMW', 'Tesla', 'grapes'].includes(car)) {
//code
}
引用: Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code

2. 複数のAND(&&)条件を持つ if 文の記述
OR演算子の場合と同じく、以下の書き方だと複数比較対象がある場合は読みづらくなる。
if(obj && obj.tele && obj.tele.stdcode) {
console.log(obj.tele.stdcode)
}
この場合、オプショナルチェーン (?.)の使用が記載されていた。
ここで注意が必要なのがオプショナルチェーン (?.)を使うと、エラーにならない代わりにundefined
を返すようになる。
この挙動を意図しない場合は気を付けた方がよさそう。👀
console.log(obj?.tele?.stdcode);
引用: Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code

3. null, undefined, 空の値を判定
if文を使って条件式を書くと冗長になる...
if (name !== null || name !== undefined || name !== '') {
let second = name;
}
この記述はよく見かけるかも。記述もスッキリしてみやすくなった。
const second = name || '';
引用: Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code

4. 複数の選択肢からswich文で値を選択する
複数の選択肢から条件に合うものを返したい場合はswich文のままでもいい気はする。
これは好みの問題かも!?👀
switch (number) {
case 1:
return 'Case one';
case 2:
return 'Case two';
default:
return;
}
Map オブジェクトを使用して簡略化する。
ただし、swich文は厳密等価 (===)で比較されるため挙動の差異には注意が必要。
const data = {
1: 'Case one',
2: 'Case two'
};
//Access it using
data[num]
引用: Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code

5. 単一行関数
以下のように関数内の処理が1行で収まりそうな時に使えるかも!?
function example(value) {
return 2 * value;
}
アロー関数を使ってスッキリ書ける。
const example = (value) => 2 * value
引用: Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code

6. 条件に応じた関数呼び出し
if文でコールしたい関数が異なる場合、そのまま書くとこうなる。
function height() {
console.log('height');
}
function width() {
console.log('width');
}
if(type === 'heigth') {
height();
} else {
width();
}
即時関数と条件 (三項) 演算子で書くとシンプル?
(type === 'heigth' ? height : width)()
コメントにもあったけどこっちの方が良さげ。
type === 'heigth' ? height() : width()
引用: Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code

JavaScriptのショートハンド特集パート2
Devで注目を集めてた10 Awesome JavaScript Shorthands(10 の素晴らしい JavaScript ショートハンド)って記事をみていく。

1. 配列のマージ
2つ以上の配列を合体させたい場合、concatメソッドが利用できる。
concatメソッドは既存の配列を変更せず、代わりに新しい配列を返します。
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇'].concat(apples);
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
スプレッド構文 (...) を使っとよりスッキリかけるかな。👀
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]

2. 配列のマージ(配列の最初に追加)
fruits配列の最初にapples配列のすべての項目を追加したい場合は次のように unshift()
メソッドが使用できる。
let apples = ['🍎', '🍏'];
let fruits = ['🥭', '🍌', '🍒'];
// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits, apples)
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]
- と同じくスプレッド構文 (...)を使えばより簡潔に書ける。 🥳
let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒']; // <-- here
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]

3. 配列の複製
slice()
メソッドを使用すると、配列を以下のように複製できます。
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = fruits.slice();
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]
ここでも毎度お馴染みスプレッド構文 (...)が活躍する。 😊
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = [...fruits]; // <-- here
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]

4. 分割代入
配列を操作していると以下のように値を取り出して別の変数に代入したいケースが出てくる時がある。
ただ、取り出す値が多くなると複数行書かないと行けなくなってしまう。
let apples = ['🍎', '🍏'];
let redApple = apples[0];
let greenApple = apples[1];
console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏
分割代入を利用するとスッキリ書ける✨
let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples; // <-- here
console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏

5. テンプレートリテラル
文字列の連結を行うには以下のような手法がある。
// Display name in between two strings
let name = 'Palash';
console.log('Hello, ' + name + '!');
//=> Hello, Palash!
// Add & Subtract two numbers
let num1 = 20;
let num2 = 10;
console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
//=> Sum = 30 and Subtract = 10
テンプレートリテラルを使うと${...}
でラップすることにより、任意の式を文字列に埋め込むことができる。可読性が良くなるので積極的に使って行きたいですね☺️
// Display name in between two strings
let name = 'Palash';
console.log(`Hello, ${name}!`); // <-- No need to use + var + anymore
//=> Hello, Palash!
// Add two numbers
let num1 = 20;
let num2 = 10;
console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
//=> Sum = 30 and Subtract = 10

6. forループ処理
forループ文で配列を扱うと以下のように書ける。
let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Loop through each fruit
for (let index = 0; index < fruits.length; index++) {
console.log( fruits[index] ); // <-- get the fruit at current index
}
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
for...of
文を使うともう少しスッキリ書ける。
let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Using for...of statement
for (let fruit of fruits) {
console.log( fruit );
}
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

7. アロー関数
配列をforEach()
メソッドで処理すると以下のようになる。ただ、もう少し簡潔に書きたいと思うかもしれない。
let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Using forEach method
fruits.forEach(function(fruit){
console.log( fruit );
});
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
その場合はアロー関数を使ってよりスッキリ書ける場合がある。
let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit => console.log( fruit )); // <-- Magic ✨
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

8. 配列内から特定のオブジェクトを見つける
配列内のオブジェクトを見つけるには、for ループが利用できます。
以下参考例ではApplesという値を持つオブジェクトを抽出しています。ただ、ご覧の通り記述量がそれなりにあります。
let inventory = [
{name: 'Bananas', quantity: 5},
{name: 'Apples', quantity: 10},
{name: 'Grapes', quantity: 2}
];
// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
for (let index = 0; index < arr.length; index++) {
// Check the value of this object property `name` is same as 'Apples'
if (arr[index].name === 'Apples') { //=> 🍎
// A match was found, return this object
return arr[index];
}
}
}
let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }
find()
メソッドを使用すると、次のように簡単に実現できます。
// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
return arr.find(obj => obj.name === 'Apples'); // <-- here
}
let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }
アロー関数の良さを引き出すなら以下のような書き方をすると1行でもやれちゃう。👀
let result = inventory.find(obj => obj.name === 'Apples');
console.log( result );

9. 文字列を整数に変換
parseInt() 関数は、文字列を解析して整数を返してくれます。
let num = parseInt("10")
console.log( num ) //=> 10
console.log( typeof num ) //=> "number"
文字列の前に + のプレフィックスを追加することで、同じことができる。
let num = +"10";
console.log( num ) //=> 10
console.log( typeof num ) //=> "number"
console.log( +"10" === 10 ) //=> true

10. 短絡評価
以下のようにif-else
ステートメントを使うことが多いかもしれない。
function getUserRole(role) {
let userRole;
// If role is not falsy value
// set `userRole` as passed `role` value
if (role) {
userRole = role;
} else {
// else set the `userRole` as USER
userRole = 'USER';
}
return userRole;
}
console.log( getUserRole() ) //=> "USER"
console.log( getUserRole('ADMIN') ) //=> "ADMIN"
論理演算子(||)の短絡評価を利用するとより短くかける。
function getUserRole(role) {
return role || 'USER'; // <-- here
}
console.log( getUserRole() ) //=> "USER"
console.log( getUserRole('ADMIN') ) //=> "ADMIN"