Table of contents
Introduction
Namaste, In this blog I will discuss 10 code scenarios on JavaScript Switch Statement.
Identify the output of the below program
let b="4"; switch(b) { case 4: console.log("number"); break; case "4": console.log("string"); break; }
a. number
b.string
c.nothing
d.error
e.undefined
Answer:b
Reason:The comparison is strict
Identify the output of the below program
let c="4"; switch(c){ case console.log("JS"): console.log("JS2"); break; case console.log("Py"): console.log("Py2"); break; }
a. JS,JS2
b. Py,Py2
c. JS
d. Py
e. JS, Py
Answer:e
Reason: Code on the case clause is executed and the returned value is compared which does not match hence next case is compared as well
Identify the output of the below program
let c=8; switch(c){ case 8: console.log(8); case 9: console.log(9); default: console.log("defualt"); }
a. error
b.8
c.default
d.8, 9
e.8,9, default
Answer:e
Reason: The cases do not have break hence the control falls through
Identify the output of the below program
let c= undefined; switch(c) { case undefined: console.log("Undefined"); break; case undefined: console.log("Undefined2"); }
a.Undefined, Undefined2
b.Undefined
c.Undefined2
d.error
e.nothing
Answer:b
Reason: The first matching case is executed
Identify the output of the below program
let c=4; switch(c) { case console.log("a"), console.log(c): console.log("c"); default : console.log("d"); }
a.a
b.a,c
c.a,4,d
d.a,d
e.a,4
Answer:c
Reason:The instructions on the case clause are executed. The first case does not match hence default is executed.
Identify the output of the below program
let a=10; switch(a) { case 1,2: console.log("a"); break; case 8,10,9: console.log("a2"); break; default: console.log("default"); }
a.a
b.a2
c.default
d.a2,default
e.error
Answer:c
Reason:None of the case clauses match hence default is executed
Identify the output of the below program
let a=10; switch(a) { case 8: case 10: case 8: console.log("a"); break; default: console.log("default"); }
a.default
b.a
c.error
d.nothing
e.a,default
Answer:b
Reason:The 2nd case clause matches.
Identify the output of the below program
function fx() { return 3; } let a=1; switch(a) { case console.log("JS"), fx(): console.log("case1"); default: console.log("default"); }
a.JS,case1
b.JS,default
c.JS
d.default
e.case1
Answer:b
Reason: The instructions on the case clause are executed. The first case does not match hence default is executed.
Identify the output of the below program
let a=10; switch(a) { case 1,2: console.log("a"); break; case 8,9,10: console.log("a2"); break; default: console.log("default"); }
a.a
b.a2
c.default
d.a,a2
e.error
Answer:b
Reason:The 2nd case clause matches (the last value)
Identify the output of the below program
let a=10; switch(a) { case 8: case 9: case 8: console.log("a"); break; default: console.log("default"); }
a.error
b.a
c.default
d.nothing
e.a, default
Answer:c
Reason: None of the case clause match hence default is executed