switch-case, ?, truthy/falsy
Let's explore the switch-case
statement and the ternary operator
for handling conditions without if
statements, as well as the concepts of truthy
and falsy
which determine truthiness in JavaScript.
switch-case Statement
A switch-case
statement is used when you want to compare a specific value with multiple potential values.
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// ... (more cases can be added)
default:
// Code to be executed if expression doesn't match any case
}
break and default
break
exits the switch-case statement when a condition is satisfied, preventing the evaluation of subsequent conditions.
If break
is omitted, even if a condition is satisfied, the subsequent conditions will continue to be evaluated.
default
contains the code to be executed when the given expression doesn't match any case
.
const fruit = 'Apple';
switch (fruit) {
case 'Banana':
console.log('It\'s a Banana');
break;
case 'Apple':
console.log('It\'s an Apple');
break;
case 'Grapes':
console.log('It\'s Grapes');
break;
default:
console.log('Unknown fruit');
}
// Output: It's an Apple
Conditional Statement Using Ternary Operator
The ternary operator allows you to write a simple if-else structure more concisely.
condition ? valueIfTrue : valueIfFalse
let age = 19;
let result = age >= 20 ? 'Adult' : 'Teenager';
console.log(result); // Output: Teenager
truthy and falsy
In JavaScript, every value is classified as truthy
or falsy
.
falsy
values are treated as false
, while truthy
values are treated as true
.
This concept is important in determining how values are treated in Boolean (true/false) contexts, which affects the execution of conditional statements.
Below are examples of falsy
values.
false
0
""
(empty string)null
undefined
NaN
All other values are truthy
.
let value = 0;
if (value) {
console.log('It\'s true');
} else {
console.log('It\'s false');
}
// Output: It's false
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.