$('.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.
–
–
–
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
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'
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.