I Love the JavaScript shorthand of If-else statement 😃

Photo by: Simson Petrol

So there it is! It is a long time ago that I put online a new blog post! Did a lot of other stuff then Web Development. But this time I want to share a small nice trick in JavaScript!

Yes, I love the JavaScript shorthand of the if-else statement. (For the record, the let variable is an ES6 type variable.) Check the super simple example below.

let aVar = 'A';
let conditionalVariable = aVar === 'A' ? true : false;

This example is super simple. I use this most of the times when the value of a variable needs to be based on the other variable.

In the early days of me writing an if-else statement in JavaScript was more like this:

var aVar = 'A';
if(aVar === 'A') {
var conditionalVariable = true;
} else {
var conditionalVariable = false;

But since DRY (Don’t Repeat Yourself) is a good thing to keep in mind, this is not the best code! In some cases, the normal If-else statement is more readable.

But for very simple tasks like my top example, it is less code.


As a bonus, I want to show that this does also work very good in Angular template expressions.

<strong>{{COMPONENT.incomeType === 'SELF_EMPLOYED' ? 'Self employed' : 'Employed'}}</strong>

This will avoid writing multiple HTML tags with ng-if’s:

<strong ng-if="COMPONENT.incomeType === 'SELF_EMPLOYED">
Self employed
<strong ng-if="COMPONENT.incomeType !== 'SELF_EMPLOYED'">

So hopefully this is gonna help you with writing better DRY JavaScript code!

Originally published at Raymon Schouwenaar.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.