In JavaScript, we can write an if else statement in shorthand by using the conditional (ternary) operator.
(condition) ? option1:option2;
So if the condition in the code above is true, then the first option will be executed. Otherwise, the second option will run if the condition is false.
Let’s see some examples of this below.
First, let’s go over a very simple if-else statement setup.
if(condition){
option1
} else {
option2
}
Let’s show a simple example using an if-else statement and then use our shorthand if-else code after.
var number1 = 3;
var number2 = 4;
if( number1
And now the same example above with our shorthand code.
var number1 = 3;
var number2 = 4;
var result = (number1<number2) ? "number1 is less than number2":"number2 is less than number1";
console.log(result);
#Output
number1 is less than number2
You can see how we write less code using the shorthand if-else statement.
Now let’s switch the number values to see what will happen.
var number1 = 4;
var number2 = 3;
var result = (number1<number2) ? "number1 is less than number2":"number2 is less than number1";
console.log(result);
#Output
number2 is less than number1
Let’s take a look at one last example.
Here we will simply want to iterate over one large array of numbers and split the numbers into two separate arrays based on whether the number is even or odd.
The code to use to check if a number is even or odd is usually the if-else statement:
if ((num % 2) == 0){
//Number is Even
} else {
//Number is Odd
}
So note how we replace this with our shorthand if-else statement below.
var numsArray = [1,2,3,4,5,6,7,8,9,10];
var oddArray = [];
var evenArray = [];
for( var i = 0; i<numsArray.length; i++ ){
((numsArray[i] % 2) == 0) ? evenArray.push(numsArray[i]):oddArray.push(numsArray[i]);
}
console.log(oddArray);
console.log(evenArray);
#Output
[1, 3, 5, 7, 9]
[2, 4, 6, 8, 10]
Hopefully this article has been useful in helping you understand how to use JavaScript if else shorthand statement.