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.
Factorial of a number in mathematics is the product of all the positive numbers less than or equal to a number. But there are no positive values less than zero so the data set cannot be arranged which counts as the possible combination of how data can be arranged (it cannot). Thus, 0! = 1.
The answer of 0 factorial is 1. There are no calculations, nothing! All you have to do is write down 1 wherever and whenever you see 0!
Zero is the integer denoted 0 that, when used as a counting number, means that no objects are present. It is the only integer (and, in fact, the only real number) that is neither negative nor positive. A number which is not zero is said to be nonzero. A root of a function is also sometimes known as "a zero of ."
The absolute value of a number is the magnitude of that number without considering its sign. Since 0 is zero units away from itself, the absolute value of 0 is just 0. The absolute value of 0 is written as |0| and is equal to 0.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With