DEV Community

yns
yns

Posted on

What is The Ternary Operator In JavaScript ?

Here is The syntax:
Ternary operator syntax
So basically , It is another way to write the conditional statements (if / else / else if ) in a much simpler way. It is especially used for the non-complex cases.
for example , instead of this:

let a = 4;
if (a > 4)
{
console.log("ok");
}
else
{
console.log("not ok");
}
Enter fullscreen mode Exit fullscreen mode

We can just do this:

a > 4 ? console.log("ok") : console.log("not ok");
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
jacobsternx profile image
Jacob Stern

While conditional if/else statements can be written using the ternary operator, it’s important to note that although they can simplify code, sometimes they can also make it quite terse, and harder to read.

Collapse
 
greenersoft profile image
GreenerSoft

console.log(a > 4 ? "ok" : "not ok"); 🙂