简体   繁体   中英

JavaScript Logical OR invalid assignment

I'm trying to understand how JavaScript's logical OR operator works and I am trying to recreate a code I read in a book but with my own twist to it but I keep getting a reference error when I try to run the code.

function add(a,b) {
   b || b = 1;
   return a+b;
}

My understanding is that if the left operand is false then the right operand is evaluated then the right operand's value is returned or used. With the code above, what I am trying to do is when the function is invoked and the second parameter is omitted, it would use a default value of 1 as the second value to the equation, but I keep getting a reference error that states invalid left hand assignment.

可能您想实现以下目标:

b = b || 1;

Try b || (b = 1) b || (b = 1) instead. That's also exactly what CoffeeScript generates for its ||= operator.

The problem is with operator precedence . Assignment = has lower precedence than boolean or || , therefore this

b || b = 1

is interpreted as

(b || b) = 1

which is invalid, because you cannot assign to an expression. To achieve what you want you have to tell JS you want || first and then = :

b || (b = 1)

but a more common way to express this would be

b = b || 1

In the context of your function this might not work as expected, since 0 is a valid integer value, and your code will treat it as false and substitute it with 1 . So, the correct, although more verbose, way to write your function is

 function add(a, b) {
    b = (typeof b == "undefined") ? 1 : b;
    return a + b;
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM