Javascript AND operator within assignment


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.

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.


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


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

Easy button for Guard Method

Use lodash's beautiful guard operator to access nested data like so:

// need to access obj.has.some.very.nested.stuff
var val = _.get(obj, 'has.some.very.nested.stuff');

as it handles the && stuff under the hood while being nice to use in a convenient method. Lodash _.get source code

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 >= s.length/2) || (s[i] === s[s.length -1 - i]) && palindrome(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.