Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does typeof null misbehave in switch statements?

It is commonly known that

typeof null

returns "object".

However, I have a piece of code that looks like this:

switch(typeof null){
    case "object": 
        1; 
    default: 
        3;
}

This code returns 3.

Why does "object" as returned by typeof null not cause the first branch of the case statement to be executed?

like image 359
dta Avatar asked Jan 28 '26 08:01

dta


1 Answers

You're missing break for the first case - so it falls through to the default case and returns 3.

switch(typeof null){
    case "object": 
        1; 
        break;
    default: 
        3;
}
like image 114
Amarghosh Avatar answered Jan 30 '26 22:01

Amarghosh