Reputation: 6029
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;
}
Upvotes: 11
Views: 5824
Reputation: 386560
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);
UPDATE 2023
With logical OR assignment ||=
r ||= i;
Upvotes: 2
Reputation: 655
I've been reading some of the answers here and I've come up with this summary.
r
: Assign i
to r
, in case r
is null
:r = r || i
Or
r || (r = i)
i
: Assign i
to r
, in case i
is not null
:i && (r = i)
Or
r = i || r
a || (Do Something) // Means: if `a` is `null`
!a || (Do Something) // Means: if `a` is **not** `null`
a && (Do Something) // Means: if `a` is **not** `null`
!a && (Do Something) // Means: if `a` is `null`
Upvotes: 1
Reputation: 121998
Just tested the speed of the code and the && is little bit faster (almost negligible).
Coming to the actual question, I found the place of using && instead of if
us literally short hand code of later. However I never use the code as it highly kill the readability of code reader.
As docs says
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value.
But what we are seeing here is an assignment to the a variable based on other. Of course the code works but I believe, this is just a mis usage of the convention.
Upvotes: 2
Reputation: 1359
It is indeed the same, and a technique often used by minifiers to collapse code. In this case, you can even use an ! in order to do the if as you are comparing without typecheck:
!r && (r = i);
Or use an || operator for this assignment:
r = r || i;
If you want to keep your code clear, use an if tho.
Upvotes: 0
Reputation: 28722
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;
}
Upvotes: 7
Reputation: 718
Consider you have something to print only when r=0 and i=10. then && will be use full like.
if(r==0 && i==10){
console.log('its good practice')
}
if we use seperate, like
if(r==0){
if(i==10){
console.log('its bad practice')
}
}
what will you do if you have lots of condition to check.? i suggest you to use first one.
Upvotes: -2