3

JavaScript can be a tricky language, with many gotchas. In this contrived example a simple function is returning within a switch. There is no break, as the function will immediately return.

function getUpperName (animal) {
    switch(animal) {
        case 'dog':
           return 'Dawg';
        case 'cat':
           return 'Kitty';
        default:
           return 'Unknown';
    }
}

Is this considered bad form and could it have unwanted side-effects? Or is this standard JS programming.

port5432
  • 5,889
  • 10
  • 60
  • 97

3 Answers3

3

Your code is fine. You don't need any break in this case and it won't backfire at you. It's always a good practice to check your code with JSLint.

Personally, I try to keep my functions with only single return at the end of the function because it's easier to add logging statements to the code then.

MartyIX
  • 27,828
  • 29
  • 136
  • 207
1

It's fine, it is a common practice and you have no unwanted side effects because of that, for you are actually leaving the function by returning to the caller.

Another hint. Sometimes, you could even see the following form for a switch statement, that is cleaner to me:

function getUpperName (animal) {
    switch(true) {
        case animal === 'dog':
           return 'Dawg';
        case animal === 'cat':
           return 'Kitty';
        default:
           return 'Unknown';
    }
}
skypjack
  • 49,335
  • 19
  • 95
  • 187
1

Not using use break inside a switch is completely standard, and its behavior is well-defined.

For example:

[0, 1, 2, 3].map(function f(n) {
  var r = 0;
  switch(n) {
    case 2: ++r;
    case 1: ++r;
  }
  return r;
}); // [0, 1, 2, 0]

However, most people think this behavior is counter-intuitive. So they prefer stepping out of the switch at the end of the case. So they use break. If you want to step out of the function too, you can use return.

Oriol
  • 274,082
  • 63
  • 437
  • 513