DEV Community

Discussion on: Switch is ok

Collapse
 
vonheikemen profile image
Heiker

The best thing about switch statements is that you're not limited to strings.

function fun(data) {
  switch(data.constructor) {
    case Symbol:
      return 'You gave me a symbol';
    case String:
      return 'No strings attached';
    case Array:
      return 'To map or not to map';
    case Number:
      return 'something something 42';
    case Boolean:
      return 'is it true?';
    case Promise:
      return 'maybe, maybe not';
    case Function:
      return "Don't call us, we'll call you";
    case (async () => {}).constructor:
      return 'Ooh, fancy stuff';
    default:
      return 'what?'
  }
}

const some_fun = function() {};
const async_fun = async function() {};

fun(['hello']);
fun(74);
fun('this');
fun(Symbol('What?'));
fun(true);
fun(some_fun);
fun(async_fun);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
macsikora profile image
Pragmatic Maciej

Nice. Thanks for sharing