Javascirpt Ternary Operator

It is the only operator with three operations. It is also used as an abbreviation for conditional statement. JavaScript can be used as an abbreviation for the Ternary If statement.

Javascirpt Ternary Operator
Javascirpt Ternary Operator

Spelling rule:

condition ? true : false


If the condition is true, the operator returns the value of expression, otherwise returns expression 2.

Ternary Operator Examples

Example 1: Transferring the result obtained with the ternary operator to a variable

var variable = Math.PI > 4 ? "Hımmm" : "maybe";

Example 2: You can use a value generated by ternary as a direct result. change of the amount to be paid according to the value of the state variable.

"Total debt:"+ (status? "75₺" : "10₺")

Example 3: You can use the Ternary operator as multiple.

var firstControl = false, secondControl = false;
var entryInformation = firstControl? "Entry Denied": second Check? "Entry Denied": "Login Done";
 
alert (login); // Login done

Example 4: You can execute multiple operations with parentheses and commas for each state.

var stop = false, age = 23;
 
mourning> 18? (
alert ("Congratulations Login"),
location.assign ( "islem.html")
):
stop = true,
alert ("Sorry !!! You can't login.")
);

Example 5: You can use the ternary operator again to perform different operations.

var dur = false, age = 16;
mourning> 18? location.assign ("continue.html"): stop = true;

EXTRA

<div>
          <input type="text" id="username"/>
          <input type="password"  id="password"/>
          <input type="button" onclick="control();" value="Control      "/>
      </div>

     <script>
            
         function control() {
             var username = document.getElementById("username").value;
             var password = document.getElementById("password").value;
             var a = (username == "codeblogger") ? (password == "codeblogger" ? "welcome " +username : "leave dont password blank") : "leave dont username blank"
             alert(a)
         }

     </script> 

One thought on “Javascirpt Ternary Operator

Add yours

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started