JavaScript Assignments for React Preparation
Basic Level
Ternary Operator
1. Create a function `getGreeting` that takes a boolean `isMorning` as input and returns:
- "Good morning" if `isMorning` is true.
- "Good evening" otherwise.
Example:
const getGreeting = (isMorning) => {
// Your code here
};
console.log(getGreeting(true)); // "Good morning"
console.log(getGreeting(false)); // "Good evening"
2. Rewrite the following `if-else` block using a ternary operator:
let message;
if (status === "loading") {
message = "Loading...";
} else {
message = "Loaded!";
}
Optional Chaining
3. Use optional chaining to retrieve the `email` of a user safely without causing an error:
const user = {
profile: {
email: "[email protected]",
},
};
console.log(user.profile?.email); // "[email protected]"
console.log(user.account?.email); // undefined
4. Write a function `getUserCity` that takes a `user` object and returns the `city` from `address`
safely. If `address` or `city` is missing, return "Unknown".
Example:
const user = { name: "Alice" }; // No address property
const getUserCity = (user) => {
// Your code here
};
console.log(getUserCity(user)); // "Unknown"
... (Additional content for intermediate and advanced levels)