Javascript AND operator within assignment
Asked Answered
H

7

86

I know that in JavaScript you can do:

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

where the variable oneOrTheOther will take on the value of the first expression if it is not null, undefined, or false. In which case it gets assigned to the value of the second statement.

However, what does the variable oneOrTheOther get assigned to when we use the logical AND operator?

var oneOrTheOther = someOtherVar && "some string";

What would happen when someOtherVar is non-false?
What would happen when someOtherVar is false?

Just learning JavaScript and I'm curious as to what would happen with assignment in conjunction with the AND operator.

Hippopotamus answered 2/7, 2010 at 5:25 Comment(3)
Try it. jsfiddle.net/uv6LRHuntington
see my answer from a related post.. #3088598Fishbowl
In your example, if someOtherVar is undefined it will throw an error. Using window.someOtherVar will allow it to take on the second value if it someOtherVar is undefined.Parch
F
119

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.

Flick answered 2/7, 2010 at 5:28 Comment(3)
Ah ok. Thanks. That makes sense as, after all, it's the reverse of the OR operator.Hippopotamus
Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false. (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)Forceps
I love the example. It would be great if you'd include a bit about && being called a 'guard' operator that's good for null checks as that's good context to have. You could even cite Douglas Crockford here: javascript.crockford.com/survey.htmlIrrigation
E
44

&& is sometimes called a guard operator.

variable = indicator && value

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

Eventful answered 2/7, 2010 at 5:37 Comment(2)
Really clear answer. The other answers left me rather baffled, but this is a very clear way of expressing it. Thank you!Tynan
I think this answer is clearly wrong. After the above statement has been executed the value of 'variable' is the value of the expression "indicator && value" whatever that may be. So the value of the variable on the left side of the assignment is set always to something. regardless of what happens on the right side (unless an error is thrown). No?Turbot
G
27

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.

Gymnastic answered 11/8, 2014 at 15:1 Comment(2)
thank you, awesome example! Help me a lot to understand && and || operators! +1Deina
Thank you for this answer! I'm curious how long will JS keep trying to access the deepest level property? For example, if you were waiting for a response to hit your backend, is it safe to use var x = y && y.z ?Chanterelle
B
20

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

Breakwater answered 2/7, 2010 at 5:28 Comment(1)
Crockford also calls it the 'guard operator' here: javascript.crockford.com/survey.htmlIrrigation
E
3

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".

Emmaline answered 11/8, 2014 at 16:17 Comment(0)
F
1

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.)

Fayum answered 12/7, 2021 at 9:27 Comment(0)
W
0

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.

Wingding answered 3/4, 2017 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.