Progress
By now, this is what the knowledge map should look like. 30% of the concepts in this course are complete.
Refactoring if conditions
This takes care of the if else if vindaloop.
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";
}
}
//becomes this via nullish coalescing.
const getPushMessage = status => {
const messages = {
received: "Restaurant started working on your order.",
prepared: "Driver is picking up your food.",
en_route: "Driver is cycling your way!",
arrived: "Enjoy your food!"
};
return messages[status] ?? "Unknown status";
}
Try it
Refactor the getStatus function and avoid using if conditions.
const getStatus = (host, user, booking) => {
if (booking.status === "pending") {
return `Hey ${user}, we're awaiting confirmation from ${host}.`;
} else if (booking.status === "confirmed") {
return `Hey ${user}, ${host} is excited to be hosting you.`;
} else if (booking.status === "canceled") {
return `Unfortunately ${user}, ${host} has canceled your booking request.`;
} else if (booking.status === "done") {
return `${host} hopes you had a great stay.`;
} else {
return "Unknown booking status."
}
}
//Solution
const getStatus = (host, user, booking) => {
const messages = {
pending: `Hey ${user}, we're awaiting confirmation from ${host}.`,
confirmed: `Hey ${user}, ${host} is excited to be hosting you.`,
canceled: `Unfortunately ${user}, ${host} has canceled your booking request.`,
done: `${host} hopes you had a great stay.`,
}
return messages[booking.status] ?? "Unknown booking status."
}
Implicit conversion and falsy values
MDN Docs The second condition in this statement will not output. Why?
const name = "Sam";
const number = 0;
if (name) {
console.log("First condition");
}
if (number) {
console.log("second condition")
}
These are "falsy values" - meaning they will be converted to false.
- false (is already a boolean)
- null
- undefined
- 0
- NaN
- "" (empty string)
Logical Not
if (!true); //false
if (!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.