ptyskju
ptyskju

Reputation: 315

How does that switch case work in JS? What does mean switch(true)?

I am currently working on project, where are parts of code that I don't understand. One of them you can see below (written in JS):

  switch (true) {
    case parseInt(data):
      return 'data';

    case parseInt(row):
      return 'row';

    default:
      return 'default';
  }

I created JSFiddle to test this switch(true) statement and to see how it behaves. It always returns 'default' string. Can someone explain to me what is happening there, please?
JSFiddle switch test

Upvotes: 3

Views: 215

Answers (2)

Duncan Lukkenaer
Duncan Lukkenaer

Reputation: 13974

A switch in JavaScript simply compares if the value of the case is strictly equal (===) to what’s inside the switch (in this case true). This is usually used to compare strings, but booleans would also work, although it is less common. Take the following example:

switch (true) {
    case 1 + 1 === 3:
        return 'A';
    case 2 * 2 === 4:
        return 'B';
    default:
        return 'C';
}

This code would return 'B' as it is the first case to match true. If none of the cases would match true, it would return 'C'.


Regarding your specific scenario; I would recommend rewriting your code to the following:

if (parseInt(data) === true) {
    return 'data';
}

if (parseInt(row) === true) {
    return 'row';
}

return 'default';

This code does the exact same thing as yours, but it is immediately clear to the reader what is happening.

I am not sure what your goal is with this function, so I cannot recommend the best way to solve your problem. Although, I can explain to you why it might not be working.

The parseInt function will always return a number or NaN (in case the input cannot be parsed). Although a number can be truthy, it will never be strictly true. That's why your function always returns 'default'. Again, I don't know what your goal is, but you might want to check if the value is truthy instead of true:

if (parseInt(data)) {
    // Data can be parsed to a number and is not 0 
    return 'data';
}

if (parseInt(row)) {
    // Row can be parsed to a number and is not 0
    return 'row';
}

return 'default';

Upvotes: 5

Cuong Vu
Cuong Vu

Reputation: 3733

It'll execute the first case that evaluates to true. If no case is true, it'll execute the default block

For example:

switch (true) {
  case 1 === 1:
    console.log('ok1');
    break;
  case 2 === 2:
    console.log('ok2');
    break;
  default:
    console.log('not ok');
}
will console.log('ok1')

Upvotes: 0

Related Questions