Explain Codes LogoExplain Codes Logo

How to write an inline IF statement in JavaScript?

javascript
prompt-engineering
best-practices
performance
Nikita BarsukovbyNikita Barsukov·Oct 23, 2024
TLDR

JavaScript's ternary operator allows for quick, inline logical evaluations. Try this format: (condition) ? trueValue : falseValue.

let access = age >= 18 ? 'Adult' : 'Minor'; // Welcome to adulthood or back to highschool?

This simple change can streamline your code, trimming an if-else block down to a single line.

The power of ternary

Ternary operators in JavaScript are a gift to developers seeking clean, concise code. They're perfect for quick evaluations that lead to one of two outcomes, controlling complexity and enhancing readability.

To illustrate, here's an if-else block:

let access; if (age >= 18) { access = 'Adult'; // Congratulations, you can vote now! } else { access = 'Minor'; // Hang in there, Fortnite is still fun! }

Through the magic of JavaScript's ternary operator, we achieve the same outcome with significantly fewer lines:

let access = age >= 18 ? 'Adult' : 'Minor'; // Congrats or sorry, no change in line count!

Truthiness in JavaScript

Understanding truthiness and logical operators becomes vital to controlling flow in JavaScript.

let canVote = (age !== null) && age >= 18; // Null age can't vote, or can they?

Here, the value of canVote will be true if age is not null and age is at least 18. In other words, no age, no vote; under 18, also no vote.

Getting logical with operators

At times, you run across situations where you need to evaluate an if without an else. In these circumstances, logical operators such as && (AND) and || (OR) can be indispensable tools.

let visibility = isLoggedIn && hasPermission; // -> Anonymous ninjas are not allowed to sneak in!

Above, visibility is assigned isLoggedIn if isLoggedIn is falsy; otherwise, it assigns hasPermission.

Keeping tidy nested conditions

At times you are met with the necessity of nested ternary operators. While they pack power in one line, readability could be at stake:

let greeting = isMorning ? 'Good morning' : (isEvening ? 'Good evening' : 'Hello'); // -> Always wanted my own greeting robot!

Nested there, isn't it? And a tad confusing? For more complex situations, consider using if-else.

Unaccompanied if statement for inline

There are instances where you need nothing but if statement inline and you can accomplish it as follows:

if (exists) performMagic(); // -> Poof! Or, you know, just a function call.

No hurry to pair it with curly braces as long as it's a single-line statement.

The tale of performance

Though the ternary operator simplifies your code, don't expect a huge performance boost. Modern JavaScript engines are pretty good at optimization, so the effect on performance is negligible. Writing legible, clean, and understandable code should always be your primary focus.