1
a = 'A';
b = null;

const w = a === b;
const x = a && a.length;
const y = b && b.length;
const z = (a && a.length) || (b && b.length);
const u = (a && a.length) && (b && b.length);

console.log(typeof w); // boolean
console.log(typeof x); // number 
console.log(typeof y); // object
console.log(typeof z); // number 
console.log(typeof u); // object

I was expecting all of them to be boolean! Can you please help me understand why some of them are not boolean ?

It is not obvious to me why short-circuit evaluation results in different z and u types.

Kaya Toast
  • 5,267
  • 8
  • 35
  • 59
  • Does this answer your question? [Does JavaScript have "Short-circuit" evaluation?](https://stackoverflow.com/questions/12554578/does-javascript-have-short-circuit-evaluation) – A. L Jun 08 '20 at 05:22
  • Can you be more specific what kind of answer you are looking for, other than "because that's what the documentation says"? – Jörg W Mittag Jun 08 '20 at 05:25
  • 1
    b is null, and null is considered an object type. It's odd, but yeah, welcome to javascript – A. L Jun 08 '20 at 05:40

2 Answers2

1

x, y, z, u are short circuit evaluations and not conditions.

const x = a && a.length;

What that means is assign a.length to x is a exists and so on. Hence a number.

Whereas if you were to put them inside an if condition they would be implicitly type casted to boolean

const a = null || "works!"
console.log(a)

If you run the above snippet you will realise how || works. If the value on the left of || evaluates to false then value on right is returned otherwise left value.

kooskoos
  • 4,622
  • 1
  • 12
  • 29
1

const x = a && a.length; // a.length = 1
const y = b && b.length; // b = null
const z = (a && a.length) || (b && b.length); // a.length = 1
const u = (a && a.length) && (b && b.length); // b = null

a && a.length // ===> true and 1
b && b.length // ===> false and next line;

x || y if x is true return x and y not exec, if x is false return y;

x && y if x is true return y, if x is false return x;