Javascript AND operator within assignment

22,680

Solution 1

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

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

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.

Solution 4

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

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

Share:
22,680

Related videos on Youtube

Alex
Author by

Alex

I'm a web and mobile software engineer! Passionate about ruby and javascript.

Updated on July 16, 2021

Comments

  • Alex
    Alex almost 3 years

    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.

    • icktoofay
      icktoofay almost 14 years
    • Chance
      Chance almost 14 years
      see my answer from a related post.. stackoverflow.com/questions/3088098/…
    • Rich
      Rich almost 9 years
      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.
  • Alex
    Alex almost 14 years
    Ah ok. Thanks. That makes sense as, after all, it's the reverse of the OR operator.
  • ctaymor
    ctaymor almost 10 years
    Really clear answer. The other answers left me rather baffled, but this is a very clear way of expressing it. Thank you!
  • Lucky
    Lucky almost 9 years
    thank you, awesome example! Help me a lot to understand && and || operators! +1
  • Bardelman
    Bardelman over 8 years
    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/…‌​)
  • Akrikos
    Akrikos about 8 years
    Crockford also calls it the 'guard operator' here: javascript.crockford.com/survey.html
  • Akrikos
    Akrikos about 8 years
    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.html
  • Scott Savarie
    Scott Savarie over 6 years
    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 ?
  • Panu Logic
    Panu Logic over 3 years
    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?