19 - Advanced Control Flow
19 - Advanced Control Flow
id=1608
Let's say you're building an app like Deliveroo, and you have a method that sends push notifications to your
users, updating them on the progress of their order:
const getPushMessage = status => {
if (status === "received") {
return "Restaurant started working on your order.";
} else if (status === "prepared") {
return "Driver is picking up your food."
} else if (status === "en_route") {
return "Driver is cycling your way!";
} else if (status === "arrived") {
return "Enjoy your food!";
} else {
return "Unknown status";
}
}
This is a very verbose way to deal with it. We can refactor it by creating an object that contains all possible
messages, with the key of that object being the status. Let's refactor it:
Notice how we also used nullish coalescing to handle the else case when the status is different than the ones
we provided
Notice how we also used nullish coalescing to handle the else case when the status is different than the ones
we provided.
In this lesson, we'll explain how implicit conversion happens in boolean contexts. For example, we know that
the if statement expects a condition that evaluates to a boolean. But what happens when we give it a string or
a number?:
const name = "Sam";
const number = 0;
if (name) {
console.log("First condition");
}
if (number) {
console.log("second condition")
}
1 of 3 5/10/2025, 9:43 PM
My notes https://learnjavascript.online/app.html?id=1608
Implicit conversion
The if statement expects a boolean. However, when you provide it with a value of another type, it will
automatically convert it to a boolean. This is called implicit conversion because the conversion is occurring
automatically
How are the values converted to boolean? Who decides that "Sam" is true, while "" is false, and 30 is true
while 0 is false?
Falsy values
null
undefined
NaN
""
These values above are called falsy values because, when converted to boolean, they will be converted to
false
If you'd like to convert a boolean value to its opposite, you can use the ! operator (Logical NOT operator).
Here's how it works:
!true; // false
!false; // true
Recap
Implicit conversion happens when JavaScript expects a boolean value but is given a non-boolean value.
Implicit conversion means that JavaScript will automatically convert the value to boolean.
Falsy values are converted to false. Everything else is converted to true.
Most common falsy values are: false, null, undefined, 0, "", NaN.
The logical NOT operator ! converts a boolean value to its opposite.
Chapter Recap
Implicit conversion happens when JavaScript expects a boolean value but is given a non-boolean value.
Implicit conversion means that JavaScript will automatically convert the value to boolean.
2 of 3 5/10/2025, 9:43 PM
My notes https://learnjavascript.online/app.html?id=1608
3 of 3 5/10/2025, 9:43 PM