Javascript usage of && operator instead of if condition

Viewed 2747

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;
 }
7 Answers

I've been reading some of the answers here and I've come up with this summary.

Short Summary

  • Condition on r: Assign i to r, in case r is null:

    r = r || i
    

    Or

    r || (r = i)
    
  • Condition on i: Assign i to r, in case i is not null:

    i && (r = i)
    

    Or

    r = i || r
    

More Examples

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`
Related