0

I'm practicing Javascript and I wrote the following code by using the Switch Statement (it runs correctly):

function switchOfStuff(val) {
  var answer = "";
  switch (val) {
    case 'a':
      answer = 'apple';
      break;
    case 'b':
      answer = 'bird';
      break;
    case 'c':
      answer = 'cat';
      break;
    default:
      answer = 'stuff';
  }
  return answer;
}

console.log(switchOfStuff('a'));

By substituting the Switch statement with a chaining if else statement I get the same output ("apple").

function switchOfStuff(val) {
  if (val = 1) {
    return "apple";
  } else if (val = 2) {
    return "bird";
  } else if (val = 3) {
    return "cat";
  } else {
    return "stuff";
  }
  return answer;
}

console.log(switchOfStuff('a'));

Both the snippets require 13/14 lines of code and return the same output: is there any reason why I should opt for the Switch Statement over the Chaining If Else Statement (or viceversa) and under what circumstances?

Barmar
  • 596,455
  • 48
  • 393
  • 495
franz1
  • 259
  • 2
  • 14
  • 6
    A `switch` statement expresses intend better. You want to do something depending on the value of a single variable. Generally speaking, the more specific the syntax, the clearer the intend, IMO. However, for this specific case, I'd just use an object of the form `{a: 'apple', b: 'bird'}` and do something like `return answers[val] || 'stuff'`. – Felix Kling Apr 26 '19 at 22:24
  • 1
    https://softwareengineering.stackexchange.com/a/222153 – penleychan Apr 26 '19 at 22:24
  • https://stackoverflow.com/questions/2922948/javascript-switch-vs-if-else-if-else – BJohn Apr 26 '19 at 22:31
  • 1
    Your `if` statements are all wrong. You need to use `==`, not `=`. – Barmar Apr 26 '19 at 22:45
  • @Barmar the output I get is the same in this case. Is there any other circumstance where using '==' instead than '=' returns a different output? – franz1 Apr 27 '19 at 05:46
  • There's no way it can produce the same output. It should always output `apple`. When you write `if (x = y)` it's essentially the same as writing `x = y; if (x)` – Barmar Apr 29 '19 at 19:27
  • Your second snippet doesn't even make much sense. You're passing a letter to the function, but then testing it against a number. – Barmar Apr 29 '19 at 19:29
  • 1
    Try passing `'b'` to both functions. The first will print `bird`, the second will print `apple` again. – Barmar Apr 29 '19 at 19:30
  • 1
    It's just coincidence that you get the same answer in the two examples you gave. The functions will work differently with different inputs. – Barmar Apr 29 '19 at 19:33

0 Answers0