Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 953
Tool Avatar asked Sep 14 '18 06:09

Tool


People also ask

Why is 0 factorial and 1 factorial equal?

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.

How do you solve zero factorial?

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!

What does 0 mean in maths?

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 ."

What is the value of 0?

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.


1 Answers

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)

like image 141
Maxime Chéramy Avatar answered Sep 23 '22 12:09

Maxime Chéramy