The problem is not with the typeof
, but you've missed the break
statement in the case. That'll make the case
like function OR object
and execute the block of both the cases.
You missed the break;
statement for the case
s. This is the reason, of falling out in the next case
.
The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
var caseObj = function() {
}
switch (typeof caseObj) {
case "function":
document.write("it is function");
break;
case "object":
document.write("It is object now");
break;
}
From the comments in the answer:
But without break it also fall-down if there is not matching case and exit from switch.But it executing case "object": statment as well.Why?
From MDN
If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.
The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.