Reputation: 12488
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.
Upvotes: 19
Views: 7572
Reputation: 2625
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'
Upvotes: 3
Reputation: 18821
The documentation about the &&
operator says:
expr1 && expr2
: Returnsexpr1
if it can be converted tofalse
; otherwise, returnsexpr2
.
This is why is returns the first value: 0
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)
Upvotes: 25