I have following code snippets.
var caseObj = function () {
}
switch (typeof caseObj) {
case \"function\":
console.log(\"it is function\");
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.
You didn't have a break statement ending each case clause. When you do this, the control flow passes to the statements of the next case clause, not matter the case condition is not satisfied. For instance if you have:
var x = 1;
switch(x) {
case 0: console.log(0);
case 1: console.log(1);
case 2: console.log(2);
case 3: console.log(2);
}
The output would be:
1
2
3
but if you put the break in each case
var x = 1;
switch(x) {
case 0: console.log(0);break;
case 1: console.log(1);break;
case 2: console.log(2);break;
case 3: console.log(2);break;
}
the output would be just 1
The switch
execution begins at the first case
that matches the requested value, beginning from the top.
Then, unless you use a break
somewhere, it will continue to execute all case
s from the first that matches to the bottom.
As an example, if you invert your 2 case
s in your example, it will only output "it is function".