switch-case with return and break
break
tells javascript to stop evaluating cases in the switch
block. Code execution continues past the closing switch
bracket. The return
statement in the example code will indeed prevent further of anything past it, including other case
statements and anything following the switch
block.
I put a break
statement in every case by habit. If I wrote a case without a break
then I might copy and paste blocks of code around in the future and the lack of a break
statement would become a bug like so:
function whereLivesA(species){
switch(species){
case 'worms':
// Relying on return to prevent further code execution within the switch
// block works but is ~bad~ smelly (according to plato :D)
var habitat = 'dirt'
return (species + ' live in ' + habitat);
case 'bees':
var habitat = 'hive';
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesA');
console.log(whereLivesA("worms"));
console.log(whereLivesA("bees"));
/* Output:
whereLivesA
worms live in dirt
bees live in hive
*/
function whereLivesB(species){
switch(species){
case "worms":
// what if future code changes remove `return` and don't add `break`?
// return (species + ' live in ' + habitat)
var habitat = 'dirt';
// break;
case "bees":
var habitat = 'hive'
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesB');
console.log(whereLivesB("bees"));
console.log(whereLivesB("worms"));
/* Output:
whereLivesB
bees live in hive
worms live in hive
*/
function whereLivesCorrect(species){
switch(species){
case "worms":
var habitat = 'dirt';
break;
case "bees":
var habitat = 'hive'
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesCorrect');
console.log(whereLivesCorrect("bees"));
console.log(whereLivesCorrect("worms"));
/* Output:
whereLivesCorrect
bees live in hive
worms live in dirt
*/
JS newbies: If you don't want to save it to a file and run node filename
, you can press F12 and paste this script or other self contained scripts into your browser's console to run it.
If you use node.js you can also type node
at a command line to start a node
console and paste it there.
The break;
statement may have been there before the return
statement was introduced. As such, it has become redundant and can be removed.
In fact, when you run that code through jslint, it will show this error:
Unreachable 'break' after 'return'.
Whether or not to heed this advice is up to you; it could be helpful during development if you're trying out a few things before settling on a particular style.
This is an alternative writing style that some might argue is a better practice:
var retval = null;
switch (something) {
case 'alice':
retval = something;
break;
// ...
}
return retval;