How to use Conditional Operator in Javascript

Description

The conditional operator has the following form:

variable = boolean_expression ? true_value : false_value;

If boolean_expression is true, then true_value is assigned to the variable.

If boolean_expression is false, then false_value is assigned to the variable.

Example


var num1 = 1;
var num2 = 2;
var max = (num1 > num2) ? num1 : num2;
console.log(max);

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions