What is the purpose of a `switch` statement in JavaScript?
A
To define a loop B
To execute code based on multiple conditions C
To declare variables D
To create a function
Analysis & Theory
The `switch` statement evaluates an expression and matches it to a case for multiple conditional paths.
What keyword is used to define different conditions in a `switch`?
A
if B
else C
case D
when
Analysis & Theory
`case` is used to specify different values to match against in a `switch` statement.
What is the purpose of the `break` statement in a `switch` block?
A
To repeat a case B
To exit the switch after a match C
To skip all cases D
To continue to the next case
Analysis & Theory
`break` prevents the execution from falling through to the next case.
What happens if you forget to use `break` in a case?
A
The program crashes B
Only the matched case runs C
It executes the current and all following cases D
It skips the case
Analysis & Theory
Without `break`, JavaScript continues executing the next cases (fall-through behavior).
What is the role of the `default` keyword in a `switch` statement?
A
To declare variables B
To handle unmatched cases C
To stop the switch D
To start the switch
Analysis & Theory
`default` runs if no `case` matches the expression value.
Which of the following is valid syntax for a `switch`?
A
switch x { case 1: ... } B
switch(x) { case 1: ... } C
switch[x] { case 1: ... } D
switch = x { case 1: ... }
Analysis & Theory
The correct syntax is `switch(expression) { case value: ... }`.
What does this code output?
```javascript
let color = 'blue';
switch(color) {
case 'red': console.log('Red'); break;
case 'blue': console.log('Blue'); break;
default: console.log('Other');
}```
A
Red B
Blue C
Other D
undefined
Analysis & Theory
`color` matches `'blue'`, so `'Blue'` is logged.
Can multiple `case` labels share the same block of code?
A
Yes, by stacking cases B
No, each case must be unique C
Only with numbers D
Only with `if` statements
Analysis & Theory
Yes, you can write multiple `case` lines before a single block without `break` in between.
What type of values can `switch` statements compare?
A
Only numbers B
Only strings C
Only booleans D
Any primitive value
Analysis & Theory
`switch` works with numbers, strings, booleans, and other primitive values.
What is the result of this code?
```javascript
let x = 1;
switch(x) {
case true: console.log("True"); break;
case 1: console.log("One"); break;
default: console.log("Default");
}```
A
True B
One C
Default D
Error
Analysis & Theory
`x = 1` matches `case 1`, so it logs `One`.