Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How -Infinity is converted to Boolean in JavaScript?
In JavaScript, -Infinity is considered a truthy value and converts to true when converted to Boolean. This might be surprising since negative infinity seems conceptually "negative," but JavaScript treats all non-zero numbers (including infinities) as truthy.
Using Boolean() Constructor
The Boolean() constructor explicitly converts values to their boolean equivalent:
<!DOCTYPE html>
<html>
<body>
<p>Convert -Infinity to Boolean</p>
<script>
var myVal = -Infinity;
document.write("Boolean: " + Boolean(myVal));
</script>
</body>
</html>
Boolean: true
Implicit Boolean Conversion
JavaScript also performs implicit boolean conversion in conditional statements:
<!DOCTYPE html>
<html>
<body>
<script>
if (-Infinity) {
document.write("-Infinity is truthy<br>");
}
document.write("Double negation: " + !!(-Infinity));
</script>
</body>
</html>
-Infinity is truthy Double negation: true
Comparison with Other Values
Here's how -Infinity compares to other special values in boolean conversion:
<!DOCTYPE html>
<html>
<body>
<script>
document.write("Boolean(-Infinity): " + Boolean(-Infinity) + "<br>");
document.write("Boolean(Infinity): " + Boolean(Infinity) + "<br>");
document.write("Boolean(0): " + Boolean(0) + "<br>");
document.write("Boolean(-0): " + Boolean(-0) + "<br>");
document.write("Boolean(NaN): " + Boolean(NaN));
</script>
</body>
</html>
Boolean(-Infinity): true Boolean(Infinity): true Boolean(0): false Boolean(-0): false Boolean(NaN): false
Key Points
-
-Infinityconverts totruein boolean context - Both positive and negative infinity are truthy values
- Only
0,-0,NaN,null,undefined, and empty string are falsy - The sign of infinity doesn't affect its truthiness
Conclusion
-Infinity converts to true when converted to Boolean in JavaScript. Despite being "negative," it's treated as a truthy value like all non-zero numbers.
Advertisements
