Skip to content

Latest commit

 

History

History
56 lines (53 loc) · 1021 Bytes

9. Ternary Operator.md

File metadata and controls

56 lines (53 loc) · 1021 Bytes

9. Ternary Operator

Example 1

const age = 15;
(age >= 18) ?
console.log("can vote.") : console.log("cannot vote.");

Output

cannot vote.

Example 2

// ternary operator to check the eligibility to vote
const age = 15;
const result = (age >= 18) ? " can vote." : "cannot vote.";
console.log(result);

Output

cannot vote.

Programming Task

Can you create a program to check whether a number is positive or negative?

Solution:

const number = 10;
const result = (number >= 0) ?
"The number is positive" : "The number is negative";
console.log(result);

Output

The number is positive

Programiz Quiz

Q. What is the correct ternary equivalent of the following if...else statement?

if (5 > 3) {
  greater = 5;
}
else {
  greater = 3;
}
  1. greater = 5 > 3 ? 3 : 5;
  2. 5 > 3 ? greater = 5 : 3;
  3. greater = 5 > 3 ? 5 : 3;
  4. 5 > 3 ? greater = 3 : 5;

Answer: 3