3
1

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.

JavaScript 即時関数を使って変数の初期値を分岐する

Last updated at Posted at 2020-01-09

constで変数の宣言時に初期値を代入する方法! 

即時関数とは

関数の定義時に実行される関数で以下が利用例。

var getValue = (function(){
    const a = 10;
    const b = 20;
    return a + b;
}());

// 引数もOK!
var getValue2 = (function(a, b){
    return a + b;
}(10, 20));

やり方

// BEFORE : letで一度宣言する書き方
const score = getScore();
let grade;
if(score > 80){
  grade = 'Good';
}else if(score > 40){
  grade = 'Normal';
}else{
  grade = 'Bad';
}

// AFTER : 即時関数+constで初期値代入
const score = getScore();
const grade = (function (value){
  if(value > 80){
    return 'Good';
  }else if(value > 40){
    return 'Normal';
  }else{
    return 'Bad';
  }
}(score));

別にif文じゃなくてもswitch文でもOK

追記:アロー関数使う場合

const score = getScore();
const grade = ((score) => {
  if(value > 80){
    return 'Good';
  }else if(value > 40){
    return 'Normal';
  }else{
    return 'Bad';
  }
})(score);
3
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?