I Love the JavaScript shorthand of If-else statement 😃

Image for post
Image for post
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.

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:

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.

Bonus

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

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

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

Originally published at Raymon Schouwenaar.

Written by

I write stories about Frontend Dev, JavaScript, Typescript, Angular, NodeJS, Serverless Functions, JAM Stack, FaunaDB, Netlify, Apple, iOS— https://byrayray.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store