AppDividend
Latest Code Tutorials

Javascript Ternary Operator Tutorial | Condition Operator Example

0

Javascript Ternary Operator Tutorial | Condition Operator Example is today’s topic. The conditional or ternary operator is the only JavaScript operator that takes the three operands.  This operator is frequently used as the shortcut for the if statement. The ternary operator is the conditional operator and can effectively and efficiently replace several lines of if statements. It verifies merely if the condition is true or false and returns the expression or carry out an operation based on the state of the condition, in probably one line of code.

Javascript Ternary Operator Tutorial

The syntax for Javascript Ternary Operator is following.

condition ? expressionA : expressionB

If the condition is true, then the operator returns the value of expressionA; otherwise (when the condition is false) it returns the value of expressionB.

Let’ s see the following example.

// app.js

const merit = 101;
const point = (merit >= 100) ? 'Clear' : 'Fail';
console.log(point);

The output is following.

Javascript Ternary Operator Tutorial

Chaining of Conditional Operators

The ternary operator is right associative, which means it can be “chained” in the following way.

// app.js

const result = (merit) => {
	return merit > 100 && merit < 150 ? 'Pass'
	     : merit > 150 && merit < 200 ? 'Second Class'
             :'First Class';
}
console.log(result(201));

The output is following.

 

Chaining of Conditional Operators

If we write the above code in an if-else statement then it will be like following.

// app.js

const result = (merit) => {
   if (merit > 100 && merit < 150) {
	return 'Pass'
   }
   else if(merit > 150 && merit < 200) {
	return 'Second Class';
   }
   else {
	 return 'First Class'
   }
}

Finally, Javascript Ternary Operator Tutorial | Condition Operator Example is over.

Leave A Reply

Your email address will not be published.

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