Help us understand the problem. What is going on with this article?

JavaScript基礎 Switch

More than 1 year has passed since last update.

JavaScript勉強中につき、以下の書籍を読んでいるのですが、学んだことを残そうと思います。

JavaScript パターン(優れたアプリケーションのための作法)

switchの書き方

読みやすさと堅牢さを考慮すると以下にするのがベストです。

var expression = 0,
    result = '';

switch(expression){
case 0:
  result = "zero";
  break;
case 1:
  result = "one";
  break;
default:
  result = "unknown";
}

switchとcaseは揃えて、case内のコードのインデントを下げます。
caseの最後は必ずbreakで終わらせます。
breakを忘れるとcase1,case2内の処理を行います。

var expression = 0,
    result = '';

switch(expression){
case 0:
  result = "zero";
  console.log(result);
case 1:
  result = "one";
  console.log(result);
  break;
default:
  result = "unknown";
}
// 実行結果は以下
// zero
// one

breakが省略されると、次のcaseを満たすかどうかに関係なく次のcase内のコードが実行されてしまいます。
なので複数のcaseに対応させたい場合は以下のように書くこともできます。

var expression = 0,
    result = '';

switch(expression){
case 0:
case 1:
  console.log("0でも1でもここを表示")
  break;
default:
  result = "unknown";
}
// 実行結果は以下
// 0でも1でもここを表示

以上switch文についてでした。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away