switch-case, ?, truthy/falsy
Let's explore the switch-case statement and the ternary operator for handling conditions without the if statement, as well as the concept of truthy and falsy values which determine truthiness in conditions.
switch-case Statement
The switch-case statement is used when you want to compare a specific value against multiple possible cases.
switch (expression) { case value1: // Code to execute if expression matches value1 break; case value2: // Code to execute if expression matches value2 break; // ... (additional cases can be added as needed) default: // Code to execute if the expression matches no cases }
break and default
The break keyword in a switch-case statement ensures that once a matching case is found, no further cases are evaluated, and the control exits the switch block.
If break is omitted, the code will continue to evaluate the next cases even if a match has been found.
The default section is where you place the code that should execute if none of the cases match the expression.
const fruit = 'apple'; switch (fruit) { case 'banana': console.log('It is a banana'); break; case 'apple': console.log('It is an apple'); break; case 'grape': console.log('It is a grape'); break; default: console.log('Unknown fruit'); } // Output: It is an apple
Using the Ternary Operator
The ternary operator allows you to express a simple if-else structure more concisely.
condition ? valueIfTrue : valueIfFalse
let age = 19; let result = age >= 20 ? 'Adult' : 'Teen'; console.log(result); // Output: Teen
truthy and falsy
In JavaScript, all values are classified as either truthy or falsy.
Falsy values are those that are treated as false in boolean contexts, while truthy values are treated as true.
This concept determines how values are converted to Boolean (true or false) and which code blocks are executed in conditional statements.
Here are some examples of falsy values:
- false
- 0
- "(empty string)
- null
- undefined
- NaN
All other values are considered truthy.
let value = 0; if (value) { console.log('This is true'); } else { console.log('This is false'); } // Output: This is false
In a switch-case statement, omitting break does not prevent the next condition from being checked.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result