DEV Community

Cover image for JavaScript if shorthand without the else
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

JavaScript if shorthand without the else

At one point in your career, you'll find yourself using the ternary operator in JavaScript a lot.

It's a fancy word for the if...else shorthand version.

Let's recheck the example.

// Full if else

let result = '';
if (our_value) {
  result = 'we got a value';
} else {
  result = 'no value';
}

// Ternary
result = our_value ? 'we got a value' : 'no value';
Enter fullscreen mode Exit fullscreen mode

So that's already a set working example.

If without the else

However, sometimes we might want to execute or set something if a specific condition is met.

Let's look at the following example.

if (our_value) {
  alert('I have the value');
}
Enter fullscreen mode Exit fullscreen mode

This piece of code should alert the user if the our_value condition is truthy.

There is no else involved.

We could write it like this:

our_value ? alert('I have the value') : null;
Enter fullscreen mode Exit fullscreen mode

However, we don't need the null value as it doesn't do anything, so we can switch to using the && operator.

our_value && alert('I have the value');
Enter fullscreen mode Exit fullscreen mode

Way cleaner, we tell the script if we do have this truthy value, we should alert the user.

Nullish default value

In some cases, you might have a function that returns some value, but you might want to return a default value if the object is nullish.

const name = null;
const user = {
  username: name ? name : 'John Doe',
};

console.log(user);
// { username: 'John Doe' }
Enter fullscreen mode Exit fullscreen mode

That example works perfectly fine. However, it's a bit duplicated again. We can leverage the ?? operator to set a default return value.

This ?? operator is called a logical nullish operator.

const user = {
  username: name ?? 'John Doe',
};
Enter fullscreen mode Exit fullscreen mode

This will either return the value of name, and if that doesn't exist, it will return John Doe.

Note: Be careful when the value can be false as it will return false in that case.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (6)

Collapse
 
moopet profile image
Ben Sinclair

I don't like using && or || like that. Sure, it works, but it means you're putting the condition expression and the action on the same line.

I prefer

if (expression) {
  action();
}
Enter fullscreen mode Exit fullscreen mode

to either of these:

if (expression) action();
expression && action();
Enter fullscreen mode Exit fullscreen mode

For anything other than the simplest cases, they start to get too long to fit on one line. This means that you either wrap or break at some point, which is ugly, or you mix and match - some of your if blocks are blocks and some are shortcuts like this. Inconsistency makes things harder to read.

Finally, including two things on one line makes it less obvious what's changed - your version control diff will highlight that line regardless of whether someone has changed the condition or the action.

Collapse
 
nombrekeff profile image
Keff • Edited

Came to say exactly this!!

I will also add that this is very confusing for people that don't know JS, as many languages will not let you do this for a reason. I've never liked the way JS handles boolean logic and comparisons, I much prefer this:

if(value === null) doStuff();
Enter fullscreen mode Exit fullscreen mode

than this:

if(!value) doStuff();
Enter fullscreen mode Exit fullscreen mode

For me it's wrong to do it in this way, mixing pears with apples. I've seen hundreds of bugs related to this, for a reason, it's a mess. And using && for flow control is also a mess and will harm you sooner or later.

Collapse
 
dailydevtips1 profile image
Chris Bongers

I don't really want to go into wether it's readable.
To me it's a personal or styleguide issue.

I'm just here to explain how it's done in this case.
I personally don't like wrapping in unneeded if's.

People working on the codebase will understand if that's your default.
But like I said it's up to the styleguide to decide that, doesn't make this faulty or wrong.

Do however really appreciate the other side you raised here, so thank you for that πŸ’–

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

Code should be easily readable by others.

when you write this:

"use strict";
let our_value = 'a';
let result = '';
if (our_value) {
  result = 'we got a value';
} else {
  result = 'no value';
}
console.log( result );
Enter fullscreen mode Exit fullscreen mode

Terser compress this to:

"use strict";let our_value="a",result="";result=our_value?"we got a value":"no value",console.log(result);
Enter fullscreen mode Exit fullscreen mode

I would always prefer the following variant:

"use strict";
let our_value = 'a';
let result = 'no value';
if ( our_value ) {
  result = 'we got a value';
}
console.log( result );
Enter fullscreen mode Exit fullscreen mode

Terser compress this to:

"use strict";let our_value="a",result="no value";our_value&&(result="we got a value"),console.log(result);
Enter fullscreen mode Exit fullscreen mode

So there is no need to mangle code.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Ah yes good point, that would always be the best option to refrain from even having the else.
Not always possible, but would advocate for that where you can.

Collapse
 
andaeiii profile image
Ande Caleb • Edited

very apt. post, this helps a lot. simple and clean.. thanks for this.