James
James

Reputation: 169

Why switch and if statement in Javascript treat boolean different, confused

I've got a switch and if problem in Javascript, the code is following.

var a=0;

if(a){
    console.log("a is true");
} else if(!a) {
    console.log("a is false");
} else {
    console.log("a is not true or false");
}


switch(a){
    case true:
        console.log("switch... a is true");
        break;
    case false:
        console.log("switch... a is false");
        break;
    default:
        console.log("switch... a is not true or false");
}

When I ran the code above, I got the result in console which confused me a lot:

a is false
switch... a is not true or false

I think it should be like this:

a is false
switch... a is false

Anyone knows why that happens? Very appreciate any answers.

Upvotes: 1

Views: 148

Answers (3)

AllTooSir
AllTooSir

Reputation: 49352

switch: The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause.

Since a=0 doesn't match either of the cases: true or false. Hence default is executed.

if-else: Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.

Since a=0 , so !a is true. This is how the condition is evaluated.

Upvotes: 1

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

If (!0) evalutes to true. Generally there is a rule anything non zero in if will evaluate to true an vie versa.

But for switch 0 will be explicitly checked against the case values and 0 is neither true or false , hence default statement gets executed.

Upvotes: 4

koljaTM
koljaTM

Reputation: 10262

0 is neither true nor false, but it is !a

Upvotes: 1

Related Questions