What's the point of having this logical operator like this: r == 0 && (r = i);
?
function do()
{
var r = 0;
var i = 10;
r == 0 && (r = i);
}
is this the same as:
if (r==0)
{
r=i;
}
What always helps me is translating it to words
var r = 0;
var i = 10;
r == 0 && (r = i);
translates to
so in short, let's forget about 1 and 2.
In javascript the execution flow in a boolean comparisan is to stop execution of if statement parameters if any part from the && fails.
An boolean comparisan will execute from left to right.
1 == 1 && 2 == 3 && (r = i)
it will pass 1 == 1
fail on 2 == 3
and never reach the assigment operation.
Basically it's a shorthand for:
if(r == 0) {
r = i;
}
Simple yes r == 0 && (r = i);
is same as
if (r==0)
{
r=i;
}
It is the same, in terms of logic and control flow.
It is shortening lines of code (code golf) by (ab)using short-circuit behavior.
The StackExchange page for code golf is https://codegolf.stackexchange.com.
For even shorter code, you could use a logical OR as default operator.
r = r || i;
Or
r || (r = i);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With