Raymon Schouwenaar

I Love the JavaScript shorthand of If-else statement 😃

Written by Raymon on , time to read ~2 minutes.

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!

comments powered by Disqus


CSS Grid Layout Metro design blocks

The times have come that we don’t have to fiddle around with Floats and Tables anymore! Flexbox is already an established term in the industry of Frontend Developers.

3 ways to loop over Object properties with Vanilla JavaScript

It happens a lot that you need to loop over an Array with JavaScript Objects! But sometimes you just don’t know what kind of properties that Object has. Lucky we are that JavaScript offers a few ways of looping over JavaScript Object properties.