JavaScript ternary operator

 JavaScript ternary operator

In JavaScript we use ternary operator or conditional operator instead of if and else statements. It actually a shorthand for if and else.

The result is a Boolean -- true or false.

condition ? true : false

Let's take a look at an example to understand this. Here, for the first time values of variable a and b are different thus it prints Nope. Next, we reassign the values to variables and make them hold five. Thus it prints Yes.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ternary operator in JavaScript</title>
    <p id="res1"></p>
    <p id="res2"></p>
        var a = 10var b = 25
        var x = document.getElementById("res1");
        var y = document.getElementById("res2");
        a===b ? x.innerHTML = "Yes" : x.innerHTML = "Nope";
        a===b ? y.innerHTML = "Yes" : y.innerHTML = "Nope";

You can also add multiple conditions. Try it as an assignment.

Post a Comment