简体   繁体   中英

Type-checking the result of operator statements

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM