Now, you might be wondering, what is a shorthand if-else statement? It’s a concise way to write if-else statements, reducing the number of lines in your code and making it easier to read and write. I’ll walk you through the nitty-gritty of this topic, ensuring you grasp the concept effortlessly.
- By using the ternary operator
- By using short-circuit evaluation with logical operators
- By using the nullish coalescing operator
Let’s explore each…
#1 – By using the ternary operator
For instance, if we want to determine if a number is even or odd, we can use the ternary operator as follows:
let number = 7; let result = (number % 2 === 0) ? "Even" : "Odd"; console.log(result);
How it works
The ternary operator first evaluates the condition number % 2 === 0. If the condition is true, it will return the expression right after the ?, which is “Even” in this case. If the condition is false, it will return the expression after the : which is “Odd”.
Here’s a step-by-step breakdown of how it works:
- If the condition is true (i.e., the number is even), the expression after the ? is executed, and “Even” is assigned to the variable result.
- If the condition is false (i.e., the number is odd), the expression after the : is executed, and “Odd” is assigned to the variable result.
- Finally, the console.log(result) command prints the value of result to the console.
#2 – By using short-circuit evaluation with logical operators
let variable = 'hello world'; let result = variable && 'variable is not empty' || 'variable is empty';
How it works
- If ‘variable’ is truthy, then ‘variable is not empty’ is returned.
- The next part is ‘|| ‘variable is empty”. Since ‘variable’ was falsy, this string is returned.
#3 – By using the nullish coalescing operator
Here’s an example:
let value1; let value2 = "Hello World"; let result = value1 ?? value2;
How it works
The nullish coalescing operator checks if the first value is null or undefined. If it is, it returns the second value; if not, it returns the first value. In the example above, since ‘value1’ is undefined, ‘result’ will be assigned the value of ‘value2’, i.e. “Hello World”.
- First, the variables ‘value1’ and ‘value2’ are declared. ‘value1’ is undefined and ‘value2’ is assigned the string “Hello World”.
- Then, the nullish coalescing operator (??) is used to assign a value to the ‘result’ variable.
- The operator first checks the value of ‘value1’. Since it is undefined, it moves on to ‘value2’.
- Since ‘value2’ is defined and not null, its value (“Hello World”) is returned and assigned to ‘result’.
- If ‘value1’ had a value other than null or undefined, that would be assigned to ‘result’ instead.
However, remember that clarity should not be sacrificed for brevity. Ensure your code is understandable, not just succinct. Shorthand If-Else statements are a tool, use them wisely.