Using Javascript && operator instead of condition
What always helps me is translating it into words
-
var r = 0;
-
var i = 10;
-
r == 0 && (r = i);
translates into
- set variable r to zero
- set variable i to ten
- if the variable r is zero AND returns the following statement "set the variable r to the value of the variable i"
- do nothing, but r is now 10.
so, in short, forget about 1 and 2.
In javascript, the flow of execution in boolean mapping is to stop the execution of the if if parameters if any part of the && & fails.
Boolean matching will be done from left to right.
1 == 1 && 2 == 3 && (r = i)
it will 1 == 1
fail on 2 == 3
and never reach an assignment.
It is mainly shorthand for:
if(r == 0) {
r = i;
}
source to share
It looks like code golf to shorten the code this way. The page for him is from the SO family - Puzzle Programming and Code Golf .
For even shorter code, you can use logical OR as the default operator.
r = r || i;
Or
r || (r = i);
source to share
It is indeed the same and the method that minifiers often use to smooth out code. In this case, you can even use! in order to execute the if if you are comparing without a typecheck:
!r && (r = i);
Or use || operator for this assignment:
r = r || i;
If you want to keep your code clean, use if tho.
source to share
Just tested the code speed and && & is a little faster (almost negligible).
Coming to the real question, I found a place to use && instead of if
us literally shorthand code later. However, I never use the code as it severely kills the code reader's readability.
As the docs says
Boolean operators are usually used with boolean (boolean) values. When present, they return a boolean value.
But what we see here is a variable assignment based on something else. Of course the code works, but I believe this is just a misuse of the convention.
source to share
You only have to print something when r = 0 and i = 10. then && will be used like.
if(r==0 && i==10){
console.log('its good practice')
}
if we use a separate one, for example
if(r==0){
if(i==10){
console.log('its bad practice')
}
}
what will you do if you have many conditions to check? I suggest you use the first one.
source to share