Roppy Barbara
Roppy Barbara

Reputation: 33

Why "if" works but "switch" doesn't work?

// It is simple code

var num = prompt("put number");
// This way is not worked 
switch (num) {
    case num > 0:
        console.log("num++");
        break;
    case num < 0:
        console.log(num-2);
        break;
}
// But this worked
if (num > 0){
    console.log(num++);
} else if (num < 0){
    console.log(num -2);
}

My first way by "switch" is not worked but "if" method worked.

I tried all of thing for changing code or other ways but the same result.

Please guys help me.

Upvotes: 1

Views: 694

Answers (3)

Elivelton Rodrigues
Elivelton Rodrigues

Reputation: 1

The switch acts as a case switcher, meaning you cannot make comparisons to create cases, just list cases by case, and perform some function from this case. The if / else structure is suitable for making comparisons, as the expected result in the if call is always a boolean.

Example:

const a = 1;

if (a === 1) {
    console.log('hello');
} else {
    console.log('sad');

switch (a) {
    case 1 : console.log('hello'); break;
    default: console.log('sad'); break;

In your case, I recommend using if/else if/else, as it is more recommended.

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

Cases cannot be expressions, you must normalize your input first.

Although it is valid to place an expression in a case, in this scenario a more tried-and-true way of dealing with this is to first normalize your input first.

You can determine direction for example:

var num = parseInt(prompt("put number"), 10);
var direction = num < 0 ? -1 : 1;

switch (direction) {
    case 1:
        console.log("num++");
        break;
    case -1:
        console.log(num - 2);
        break;
}

Upvotes: 0

Marcelo The Mage Coder
Marcelo The Mage Coder

Reputation: 2202

Because the statement num > 0 inside you case will return true or false. If you do this:

switch (true) {
    case num > 0:
        console.log("num++");
        break;
    case num < 0:
        console.log(num-2);
        break;
}

It will work.

Upvotes: 8

Related Questions