Question

This should be quite a simple question I just couldn't find the answer anywhere so thought I'd save myself some time and ask here.

I was looking at some javascript code and noticed an expression of the form:

a < b && (other maths statements);

The other maths statements are just assigning of variables and simple stuff.

My question is this. Is this another way to write compact if statements?

I know that statement?if-block:else-block; is one way to do it but as && is short-circuit and left-associative this is all I can think it would be. I know you can't have an else block with this method but it's pretty neat.

Can someone just validate I'm awake at this time in the morning please.

Thanks,

Was it helpful?

Solution

Yes, you can do it. If a is less than b the other statements are going to execute.

That said, you probably shouldn't do it. Rather than trying to save yourself a small amount of typing you should instead go with a more readable piece of code whose purpose is immediately obvious. After all, if you needed to check that you weren't misinterpreting it, other programmers who may have to read or modify your code could have the same problem.

There is also a pitfall with this if you were trying to do multiple assignments, but one of the middle assignments was for a "falsey" value. Consider this example:

a < b && (a = 1) && (b = 0) && (c = 3);

Essentially, if a is less than b, set a to 1, b to 0 and c to 3. However, the (b = 0) returns false (0 is considered false when converted to a boolean), so the (c = 3) part never executes. Obviously with that basic example anybody who is reasonably knowledgeable about JavaScript could work out that it will fail, but if the values for a, b and c were coming from elsewhere there'd be no immediate indication that it wouldn't always work.

OTHER TIPS

You can use this type of if-else statement for shorter code, although in my opinion it's less readable:

JavaScript:

var el = document.getElementById('test'),
a = 1,
b = 0;

a>b && (el.innerHTML = "True") || (el.innerHTML = "False");

HTML:

<div id="test"></div>

An example jsFiddle

If you switch the operator from greater-than to less-than, you will see "False" printed inside of the "test" DIV.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top