Ternary operator In Javascript

Posted By : Vinay Tiwari | 28-Feb-2018

This blog explains us, how to work Ternary Operator in javascript. Ternary operator can be used as a shortcut for an if...else...statement.

 

Syntax of Ternary Operator

Boolean Expression? Statements to execute if true: Statements to execute if false

Boolean expression return true or false, if the boolean expression returns true then the statements that are present after the question mark will be executed and this expression returns false then the state message is present after the colon symbol(:) will be executed.

The ternary (?:) operator can be used as a shortcut method for an if...else condition. It is widely used as part of a larger expression.

 

Check if the number is even or odd using if...else...Statement

 

Let's look at an example:-

var userInput = Number(prompt)"please enter a number");

var msg = userInput % 2 == 0 ? "number is even" : "number is odd";

alert(msg);

 

Declaration:-

 

Ternary operator will have the Boolean Expressions (userInput % 2 == 0) this will be evaluated. If this statements (userInput % 2 == 0) returns true and this string ("number is even") will be return. This string will be used to initialize this variable (msg). If this expression (userInput % 2 == 0) returns false then this string ("number is odd") will be used to initialize this variable (msg). And variable to passing the alert function. We can also do more than one single expression per example, the expression will be separating them with a comma, and it will be enclosing them within parenthesis.

 

Thanks

 

About Author

Author Image
Vinay Tiwari

Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.

Request for Proposal

Name is required

Comment is required

Sending message..