Wednesday 24 April 2019

JS Comma Operator

A mate at work asked me a question about checking things in JS. He had a case where if an object had a property he needed to check for 3 conditions, one of which was if the properties value matched a given value. If it didn't have the property then he needed just needed to check 2 conditions. He wasn't overly keen on wrapping the two conditions within a further if statement and asked if I knew of a way of combining them all into one if statement, I must admit I knew that there was one but I couldn't think of it for the life of me...

As in a particularly nasty case of athletes foot, it itched at me overnight, then I started to remember a rather obscure feature of JS which it seems it borrowed from C, the Comma Operator. In order to check that it would do what he needed to do, I wrote this simple JSFiddle:

let a;

if(true && true && a === 1, a){
  alert("First: a === 1");
}

a = 1;

if(true && true && a === 1, a){
  alert("Second: a === 1");
}

It's rather obscure though, so I'm a little concerned about using it with production code, as discussed on StackOverflow.

No comments:

Post a Comment