LoginSignup
3
3

More than 3 years have passed since last update.

[JavaScript] if文の条件で代入をしてはいけない

Last updated at Posted at 2020-01-21

JavaScriptのif文条件には truthy または falsy と認識される式が書けます。1
そして条件の中で変数に値を代入することもできます。

代入の例
if (a = 'a') { // 結果、'a'(truthy)が評価される
  console.log(a); // a
}

if (a = '') { // 結果、空文字(falsy)が評価される
} else {
  console.log(a); // ''
}

さらに、カンマ演算子を使用してこんなこともできます。

複数代入の例
if (a = 'a', b = 'b', a === 'b') {
  console.log('true');
} else {
  console.log('false'); // こっちに入る 
}

// 複数の代入もできている
console.log(a); // a
console.log(b); // b

abに代入を行なった上で、a === 'b'の評価をしています。

これはいつ使うの?

基本的に使いません。
この書き方は悪い習慣とされています。

理由

その1

比較演算子のタイプミスかどうかがわかりにくい。
もし、代入を行う際は以下のように括弧を記述することを推奨されています。

if ((a = 'a')) {}

その2

ほとんどの場合においてわかりにくい。

if ((res = myFunc())) {
  console.log(res);
}

// あえてif文で代入する必要がない
res = myFunc();
if (res) {
  console.log(res);
}

その3

スコープがわかりにくい。

if ((a = 'a')) {
  console.log(a); // a
}
console.log(a); // a

便利な場面を 無理やり 見出してみた

特定の処理だけをスキップする時に使う。

let res = null;
let err = null;
if (({res, err} = myService()), err != null) {
  throw err;
}

function myService() {
  // 何かの処理の結果
  return { res: {}, err: {name: 'hogeErr'}}
}

うーん、、Goっぽくもない気がしますが、、
やっぱり嬉しい場面がないですね、、

3
3
1

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
3
3