Skip to content

Instantly share code, notes, and snippets.

@peterekepeter
Created April 12, 2019 17:10
Show Gist options
  • Save peterekepeter/b4edce343d510c112cc8878f27eb186c to your computer and use it in GitHub Desktop.
Save peterekepeter/b4edce343d510c112cc8878f27eb186c to your computer and use it in GitHub Desktop.
JavaScript has dynamic switch case
// This example shows that in javascript even
// the case expressions in the switch is dynamic
'use strict';
let prefix = 'label';
function getLabel(n) { return prefix + n };
console.log(getLabel(1)); // prints "label1"
function print(label){
switch(label){
case getLabel(1): console.log(1); break;
case getLabel(2): console.log(2); break;
default: console.log("HELP ME!!!");
}
}
print('label2'); // prints 2
prefix = 'cow';
print('label2'); // prints "HELP ME!!!"
print('cow2'); // prints 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment