Ternary Operator in Javascript

Ternary Operator in Javascript

Lets get started:

What is a ternary operator?

A ternary operator in computer programming, is a conditional operator. The conditional statements are the decision-making statements which depends upon the output of the expression.

The ternary operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is True followed by a colon (:), and finally the expression to execute if the condition is False.

This operator is frequently used as an alternative to an if...else statement.

The syntax of ternary operator is displayed below:

condition ? exprIfTrue : exprIfFalse

The condition, exprIfTrue and exprIfFalse are the parameters/operands of operator.

condition

An expression whose value is used as a condition and that evaluates it to return a boolean value.

exprIfTrue

An expression which is executed if the condition evaluates to a true value (one which equals).

exprIfFalse

An expression which is executed if the condition is false (that is, has a value which can be converted to false).

Lets understand this with the help of an example:

Here's a simple program to determine if a student has passed the exam or failed based on his marks

let studentMarks = 78;
if(studentMarks > 40){
    console.log("You have passed the exam") //exprIfTrue
}else{
    console.log("You have failed the exam") //expxrIfFalse
}
// output: You have passed the exam

The condition i.e, studentMarks < 40 is written in braces of If statement, it checks the condition and executes the output if the condition is true, if not, the else part is when the condition is not meet and is false.

  • Now, lets do this using ternary operator and
let studentMarks = 78;
studentMarks > 40 ? console.log("You have passed the exam") : console.log("You have failed the exam")

We can see from above example, the ternary operator take a single line of expressions and is easier to use for conditional statements and evaluate it against the condition and execute the output.