Const variable = ( a && a.from && a.from.pathname ); Can someone explain me this ? Here “a” is an object

Can someone explain me what const variable = ( a && a.from && a.from.pathname ); . Here a is an object: const a ={from:{pathname: 'string'}} . I think variable a boolean value but in my book it says it’s a string . How so?

The reason is because of something called short circuiting, and in the case of the && operator what is happening in a simplified version is:

let var = 1 && 2 && 3;
console.log(var) //3
let var = 0 && 1 && 2;
console.log(var) //0

In the case of a && short circuit you are getting the last value if all values are true, but in the case a single value is false you will always assign to the false value so if you want to get the value string you need to do:

const variable = a.from.pathname;

You may want to read this if you are more interested in short circuiting with && operator

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

3 Likes

To add the crucial line from MDN:

It is typically used with Boolean (logical) values. When it is, it returns a Boolean value. However, the && operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.

So you check if the values are truthy or falsy, but you return the original type.

2 Likes

thanks @caryaharper for explaining that.

1 Like