...

/

Ternary Operators and Conditionals

Ternary Operators and Conditionals

Introduction to ternary operators and how they are used in JavaScript.

Background

Conditional statements execute code dependent on a condition. It is common for conditionals to alter program flow.

In the code snippet below, we assigned 0 or 1 depending on whether the original value is 0, 1, or -1. We wrote multiple lines of code for a single assignment, as shown below.

Press + to interact
var variable = 0;
if(variable === 0){
variable = 1;
}
else if(variable === -1){
variable = 0;
}
else if(variable === 1){
variable = 0;
}
else{
console.log("The variable is not 1, -1 or 0");
}
console.log("variable:",variable);

Although the code does fulfill our requirement, it takes 12 lines of code. This becomes troublesome when we need to use the variable’s value in an expression ahead. This is where ternary operators come into play.

Introduction

Ternary operators are a shortcut to an if-condition which executes expressions depending on whether the condition is true or ...