简体   繁体   中英

Why does “0 && true” return 0 in javascript instead of a boolean?

I was convinced that any logical expression in Javascript will return a boolean value, yet this expression returns a number 0 instead of a bool:

0 && true
> 0

Why is that so? How do I approach logical expressions in Javascript in this case to prevent this kind of mistake in the future?

Background story - I was baffled by this statement in jQuery:

$('.something').toggle(0 && true);

It doesn't toggle the element because '0' is returned, and not a boolean!

Maybe there are some clever reasons why this is so, but can't say I like it.

The documentation about the && operator says:

expr1 && expr2 : Returns expr1 if it can be converted to false ; otherwise, returns expr2 .

This is why is returns the first value: 0

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description

You expected as a result false (a boolean), however the boolean value of the resulting value is falsy too. This means that you can use it in a condition ( if ) and have the expected behavior.

If you need to store it in a variable and prefer to have a boolean value, you can convert it. This can be done using a double negation: !!

!!(0 && true)

Or using Boolean :

Boolean(0 && true)

As @Maxime Chéramy noted, JavaScript checks if the first element returns false and it doesn't really check the second one. This saves calculation time.

JS does not need to check both statements if the first is false it will not check the second one, it will just return the first one. If the first is true, again, it doesn't check the second one, it just returns it.

A number, object, array, or string are truety.

Use Boolean() to get a Boolean value or use the short method !!()

'banana' && true  // returns true

but

true && 'banana' // returns 'banana'
Boolean(true && 'banana') // returns 'true'
!!(true && 'banana') // returns 'true'

with three

true && 'banana' && 1 // returns 1
true && 1 && 'banana' // returns 'banana'
1 && 'banana' && true // returns true
Boolean(true && 'banana' && 1) // returns 'true'
!!(1 && 'banana' && true) // returns 'true'

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