We want to rewrite the following code snippet using the conditional operator:
let name; if (test) { name = "Alice"; } else { name = "Bob"; }
Which notation is correct?
let name = test : "Alice" ? "Bob";
let name = test ? "Alice" : "Bob";
let name = if test ? "Alice" : "Bob";
let name = (test)("Alice")("Bob");
Explanation & Hint:
In the conditional (ternary) operator, the condition test is evaluated. If test is truthy, the expression before the ? (in this case, “Alice”) is assigned to name. If test is falsy, the expression after the : (in this case, “Bob”) is assigned to name. By using the conditional operator, you can simplify the if-else statement into a single line. The value assigned to name depends on the condition test, resulting in the same outcome as the original if-else statement. |