The Ternary Operator in JavaScript
Learn and implement conditional programming using the ternary operator in JavaScript source code. We will see the usage and advantages of the ternary return in JavaScript programming.
Ternary Operator in JavaScript
The ternary operator helps us write the conditional statement in a small code.
Syntax:
condition_check ? condition_if_true : condition_if_false;
As shown above, the condition checks with the ?
operator. After that operator, we need to write the first expression(the successful statement), and the :
operator for the second expression will be a failed case.
A ternary operator assesses a condition and executes a piece of code based on the defined condition. If the condition is true
, the first expression will be executed, or else it will execute the second expression.
Let’s have an example with the if else
conditional statement.
Code Example:
let marks = 50;
// with if else
if (marks >= 40) {
console.log('You are passed!');
} else {
console.log('You are failed!');
}
// same task with ternary operator
marks >= 40 ? console.log('You are passed!') : console.log('You are failed!')
Output:
You are passed!
You are passed!
In the above example, we created the same conditional statement with if else
and ternary ? :
operator and the results are the same. Both statements perform the same functionality, but the ternary operator is more concise.
Ternary Operator With return
Statement in JavaScript
To get a return value of a JavaScript function on conditional based, we can use a ternary operation statement with a return keyword to achieve this.
Code Example:
let marks = 80; // initialized
checkGrade(marks)
console.log('After updating marks')
marks = 70 // updating
checkGrade(marks)
function checkGrade(marks) {
return marks >= 80 ? console.log('You\'re Grade is A!') :
console.log('You\'re Grade is B!')
}
Output:
"You're Grade is A!"
"After updating marks"
"You're Grade is B!"
In the above example, we initialized the marks variable and called the checkGrade()
function with the value of the passing marks as an argument, and in the checkGrade()
function, we used the return keyword with a ternary operation statement.
If the marks are greater or equal to 80, it will print grade A in logs or else it will print Grade B. We have passed 80 marks to the function to check the true condition, and after updating marks, we have passed 70 marks to the function to check the false condition statement.