• Post author:
  • Post category:Blog
  • Reading time:2 mins read
  • Post last modified:June 12, 2024

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.

For more Questions and Answers:

JavaScipt Essentials 1 (JSE) | JSE1 – Module 4 Test Exam Answers Full 100%

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments