Control Flow

Ternary Operator in JavaScript

The ternary operator is used to execute code based on the result of a binary condition.

It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a method.


Syntax
result = binaryCondition ? valueReturnedIfTrue : valueReturnedIfFalse;

Notes

The ternary cannot be used to execute code, it must be an expression. It must be either returned in a method, or set equal to a variable with the same data type as the returned values.


Example
var findMaximum = (a > b) ? a : b;

< Switch Case   |   For Loop >

© 2018 SyntaxDB. All Rights Reserved.