What is Ternary Operator in JS

Keesha Hargrove
2 min readDec 16, 2021

Code more concisely with the ternary operator.

Often, you use the if-else statement when you need to evaluate a test to true and execute a block of code. Lets look more into this example….

When the person has reached the age of 16, the following code can be used to allow them to drive:

var age = 20;
var isDriveable;
if (age > 16) {
canDrive = 'yes';
} else {
canDrive = 'no';
}

Ternary operators have the following syntax:

condition ? expression_1 : expression_2;

If-else statement can be quickly shortened by using the ternary operator in this example:

var age = 20;
var isDriveable = age > 16 ? 'yes' : 'no';

There is only one operator in JavaScript which takes three operands, the ternary.

The condition evaluates to a true or false Boolean value. Expression_1 is returned if the condition is true; otherwise, expression_2 is returned.

Each of expression_1 and expression_2 may be any type.

JavaScript ternary operator examples

Set default parameter

Ternary operators are typically used in ES5 to set default parameters of functions, for example:

function test(num) {
bar = typeof(num) !== 'undefined' ? bar : 20;
console.log(mum);
}
test(); // 20
test(40); // 40

When the bar parameter isn’t passed, its value will be set to 20 in this example. Other than that, the bar parameter uses its passed value, which is 40 in this case.

The default parameters for a function have been improved in ES6.

--

--