Building with JavaScript Ternary Operators

ByChristopher Nathaniel |

The IF statement is the foundation of simple conditional logic found throughout programming languages. You typically compare two conditions, and if the two conditions meet under the conditional logic then the code is run.

Our basic example of an if-statement in JavaScript is as follows;

var hasAge = 40
var isAdult;

if(hasAge > 18) {
   isAdult = true;
} else {
   isAdult = false;
}

console.log(isAdult);

We could really shorten this down using whats known as a ternary operator; which is like a short-hand if statement. It works like this; and as you can see, its much cleaner syntax thats being used. When using a-lot of simple if-statements such as this, it will be worth using the ternary operator over the traditional if-statement.

var hasAge = 40;
var isAdult = hasAge > 16 ? true : false;

console.log(isAdult);

Now that we have that working, lets take a deeper look in to whats going on.

variable = condition ? expression if true : expression if false;

As you can see, variable will receive the result. Condition is our typical if-statement condition and after the ‘?’ we have our two return values separated by ‘:’. The left is our true value, and our right is our false value.

We can use this operator in more exciting ways. Lets have a look at seeing at which point we are during a day.

var now = new Date();
var response;

if(now.getHours() > 17) {
  response = "Good evening.";
} else {
  response = "Good day.";
}

console.log(response);

This can be considerably shorted to;

var now = new Date();

var response = now.getHours() > 17 ? "Good evening." : "Good day.";

console.log(response);

Lastly, we can actually chain ternary operators together. its whats known as right-associative. Let’s take a look and see how this is put together. This last one actually saves a lot-of space from using a traditional if-statement. But don’t let it get too complicated as it can quickly become unreadable. From a professional perspective its a good idea to avoid this all-together but its still very useful to know.

var now = new Date();

var response = now.getHours() > 6 ? "Good Morning."
               : now.getHours() > 12 ? "Good Afternoon"
               : now.getHours() > 6 ? "Good Evening"
               : now.getHours() > 10 "Good Night.";

console.log(response);

The ternary operator is a common tool that is used inside of JavaScript, it can make your code easy to read but can also make it unreadable if not used correctly. Try and keep everything simple, and follow the best practices.

create build imagine design code grow enhance innovate inspire prototype debug wireframe integrate optimise performance scalability UI UX
0