赋值内的 Javascript AND 运算符

我知道在 JavaScript 中你可以做到:

var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...";

其中,如果不是 nullundefinedfalse,变量 oneOrTheOther将接受第一个表达式的值。在这种情况下,它被赋给第二个语句的值。

但是,当我们使用逻辑 AND 操作符时,变量 oneOrTheOther被赋值给什么?

var oneOrTheOther = someOtherVar && "some string";

如果 someOtherVar不是假的,会发生什么?
someOtherVar为假时会发生什么?

刚开始学习 JavaScript,我很好奇赋值和 AND 操作符一起会发生什么。

23967 次浏览

Quoting Douglas Crockford1:

The && operator produces the value of its first operand if the first operand is falsy. Otherwise it produces the value of the second operand.


1 Douglas Crockford: JavaScript: The Good Parts - Page 16

Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:

true && "foo"; // "foo"
NaN && "anything"; // NaN
0 && "anything";   // 0

Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty string, and of course false, anything else coerces to true.

&& is sometimes called a guard operator.

variable = indicator && value

it can be used to set the value only if the indicator is truthy.

Beginners Example

If you are trying to access "user.name" but then this happens:

Uncaught TypeError: Cannot read property 'name' of undefined

Fear not. You can use ES6 optional chaining on modern browsers today.

const username = user?.name;

See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Here's some deeper explanations on guard operators that may prove useful in understanding.

Before optional chaining was introduced, you would solve this using the && operator in an assignment or often called the guard operator since it "guards" from the undefined error happening.

Here are some examples you may find odd but keep reading as it is explained later.

var user = undefined;
var username = user && user.username;
// no error, "username" assigned value of "user" which is undefined


user = { username: 'Johnny' };
username = user && user.username;
// no error, "username" assigned 'Johnny'


user = { };
username = user && user.username;
// no error, "username" assigned value of "username" which is undefined

Explanation: In the guard operation, each term is evaluated left-to-right one at a time. If a value evaluated is falsy, evaluation stops and that value is then assigned. If the last item is reached, it is then assigned whether or not it is falsy.

falsy means it is any one of these values undefined, false, 0, null, NaN, '' and truthy just means NOT falsy.

Bonus: The OR Operator

The other useful strange assignment that is in practical use is the OR operator which is typically used for plugins like so:

this.myWidget = this.myWidget || (function() {
// define widget
})();

which will only assign the code portion if "this.myWidget" is falsy. This is handy because you can declare code anywhere and multiple times not caring if its been assigned or not previously, knowing it will only be assigned once since people using a plugin might accidentally declare your script tag src multiple times.

Explanation: Each value is evaluated from left-to-right, one at a time. If a value is truthy, it stops evaluation and assigns that value, otherwise, keeps going, if the last item is reached, it is assigned regardless if it is falsy or not.

Extra Credit: Combining && and || in an assignment

You now have ultimate power and can do very strange things such as this very odd example of using it in a palindrome.

function palindrome(s,i) {
return (i=i || 0) < 0 || i >= s.length >> 1 || s[i] == s[s.length - 1 - i] && isPalindrome(s,++i);
}

In depth explanation here: Palindrome check in Javascript

Happy coding.

According to Annotated ECMAScript 5.1 section 11.11:

In case of the Logical OR operator(||),

expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

In the given example,

var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...move along";

The result would be the value of someOtherVar, if Boolean(someOtherVar) is true.(Please refer. Truthiness of an expression). If it is false the result would be "these are not the droids you are looking for...move along";

And In case of the Logical AND operator(&&),

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

In the given example,

case 1: when Boolean(someOtherVar) is false: it returns the value of someOtherVar.

case 2: when Boolean(someOtherVar) is true: it returns "these are not the droids you are looking for...move along".

I have been seeing && overused here at work for assignment statements. The concern is twofold: 1) The 'indicator' check is sometimes a function with overhead that developers don't account for. 2) It is easy for devs to just see it as a safety check and not consider they are assigning false to their var. I like them to have a type-safe attitude, so I have them change this:

var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex();

to this:

var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex() || 0;

so they get an integer as expected.

I see this differently then most answers, so I hope this helps someone.

To calculate an expression involving ||, you can stop evaluating the expression as soon as you find a term that is truthy. In that case, you have two pieces of knowledge, not just one:

  1. Given the term that is truthy, the whole expression evaluates to true.
  2. Knowing 1, you can terminate the evaluation and return the last evaluated term.

For instance, false || 5 || "hello" evaluates up until and including 5, which is truthy, so this expression evaluates to true and returns 5.

So the expression's value is what's used for an if-statement, but the last evaluated term is what is returned when assigning a variable.

Similarly, evaluating an expression with && involves terminating at the first term which is falsy. It then yields a value of false and it returns the last term which was evaluated. (Edit: actually, it returns the last evaluated term which wasn't falsy. If there are none of those, it returns the first.)

If you now read all examples in the above answers, everything makes perfect sense :)

(This is just my view on the matter, and my guess as to how this actually works. But it's unverified.)