JavaScript Ternary Operator

Understand The JavaScript Ternary Operator

If statement in JavaScript provides you a way to execute a block of code conditionally.

const age = 19
if (age >= 18) {
    console.log('you are old enough to drive');
} else {
    console.log('you are too young to drive');
}

However, there is a shorter way accomplish this:

const age = 19;
age >= 18 ? console.log('you are old enough to drive') : console.log('you are too young to drive');

Syntax

condition ? expression one : expression two;

As you can see in the syntax the ternary operator consists of the condition followed by two expressions. If the condition results to true, expression one is executed else expression two is executed.

Ternary operator is primarily used to conditionally assign values to the variables.

const age = 19;
const canDrive = age >= 18 ? true : false;
console.log(canDrive); // true

Recommended: How to get current date in JavaScript?

Leave a Reply

Your email address will not be published. Required fields are marked *