Thursday 3 July 2014

Chapter 10: Operators - Ternary

Ternary
Finally the last one is the Ternary operator. The general format of this is that you have a condition, you asking something, you say what happened of this is true and what happens if this is false. You can actually think of it as a many if else statements. So let me show you a example here:

Syntax:
Condition ? true : false


Default example:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<script>
var player1 = 400;
var player2 = 495;
var winner;

if (player1 < player2) {
            console.log("player2 is winner");
} else {
            console.log("player1 is winner");
}

</script>
</body>
</html>

Ternary Example:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<script>
var player1 = 400;
var player2 = 495;
var winner;

( player1 < player2 ) ? console.log("player2 is winner") : console.log("player1 is winner") ;

</script>
</body>

</html>

No comments:

Post a Comment