Javascript AND operator within assignment

JavascriptVariable AssignmentLogical OperatorsAnd Operator

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

&& is sometimes called a guard operator.

variable = indicator && value

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

Solution 3 - Javascript

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: https://stackoverflow.com/questions/14813369/palindrome-check-in-javascript/25091111#25091111

Happy coding.

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptmykhalView Answer on Stackoverflow
Solution 3 - JavascriptKing FridayView Answer on Stackoverflow
Solution 4 - JavascriptDaniel VassalloView Answer on Stackoverflow
Solution 5 - JavascriptBatScreamView Answer on Stackoverflow
Solution 6 - JavascriptTed van GageldonkView Answer on Stackoverflow
Solution 7 - JavascriptDrew DealView Answer on Stackoverflow