I’m looking to simplify my code by using a JavaScript inline if statement. How can I implement it for cleaner conditional logic?
After spending a good few years in front-end development, one quick trick I rely on a lot is using the ternary operator for writing a javascript inline if. It’s simple and keeps things readable when you have two outcomes based on a condition.
let result = (age >= 18) ? 'Adult' : 'Minor';
console.log(result);
In this example, if age
is 18 or more, it gives ‘Adult’; otherwise, ‘Minor’.
The ternary operator is honestly a lifesaver for quick, compact decisions without overcomplicating your code
Totally agree with @mark-mazay here — after working on a few high-traffic projects myself, I’d just add that sometimes, you don’t even need both true and false paths for a javascript inline if.
When you only care about doing something if a condition is true, the logical AND (&&
) trick is pure gold:
let message = isLoggedIn && 'Welcome back!';
console.log(message);
If isLoggedIn
is true, it returns ‘Welcome back!’; if not, it just quietly stays undefined
.
It’s a subtle way of writing a javascript inline if that reads naturally — perfect for clean, minimal code.
These are such good points — and building on @vindhya.rddy’s thoughts, there’s another little gem that’s super handy when using javascript inline if patterns: the logical OR (||
) operator for setting default values.
Take this example:
let username = inputName || 'Guest';
console.log(username);
Here, if inputName
is falsy (null, undefined, ‘’), it falls back to ‘Guest’.
This form of javascript inline if isn’t just compact, but also extremely helpful to guard against missing or bad data without needing if-else ladders.