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.

Syntax:
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">
<head>
    <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>
</head>
<body>
    <p id="res1"></p>
    <p id="res2"></p>
    <script>
        var a = 10var b = 25
        var x = document.getElementById("res1");
        var y = document.getElementById("res2");
        a===b ? x.innerHTML = "Yes" : x.innerHTML = "Nope";
        a=5b=5;
        a===b ? y.innerHTML = "Yes" : y.innerHTML = "Nope";
    </script>
</body>
</html>

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



Post a Comment

0 Comments

React