Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript usage of && operator instead of if condition

Tags:

javascript

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;
 }
like image 326
user2818430 Avatar asked Jul 25 '17 07:07

user2818430


Video Answer


3 Answers

What always helps me is translating it to words

  1. var r = 0;
  2. var i = 10;
  3. r == 0 && (r = i);

translates to

  1. set variable r to zero
  2. set variable i to ten
  3. if variable r equals zero AND the return of the following statement "set variable r to value of variable i"
  4. do nothing, but r is now 10.

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;
}
like image 183
Tschallacka Avatar answered Oct 14 '22 22:10

Tschallacka


Simple yes r == 0 && (r = i);is same as

if (r==0)
 {
     r=i;
 }
like image 43
Adib Rajiwate Avatar answered Oct 14 '22 22:10

Adib Rajiwate


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);
like image 28
Nina Scholz Avatar answered Oct 14 '22 22:10

Nina Scholz