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 [ ] is converted to Number in JavaScript?
In JavaScript, an empty array [] converts to the number 0 when using type coercion. This happens through a multi-step conversion process that JavaScript performs automatically.
How the Conversion Works
When converting [] to a number, JavaScript follows these steps:
- First, it calls the
valueOf()method on the array, which returns the array itself - Since the result isn't a primitive, it calls
toString()on the array - An empty array's
toString()returns an empty string"" - Finally, the empty string converts to
0
Using Number() Method
<!DOCTYPE html>
<html>
<body>
<p>Convert [] to Number</p>
<script>
var myVal = [];
document.write("Number: " + Number(myVal));
</script>
</body>
</html>
Number: 0
Step-by-Step Demonstration
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [];
document.write("Original array: " + JSON.stringify(arr) + "<br>");
document.write("toString() result: '" + arr.toString() + "'<br>");
document.write("Number conversion: " + Number(arr) + "<br>");
document.write("Using + operator: " + (+arr));
</script>
</body>
</html>
Original array: [] toString() result: '' Number conversion: 0 Using + operator: 0
Other Array Examples
<!DOCTYPE html>
<html>
<body>
<script>
document.write("Empty array []: " + Number([]) + "<br>");
document.write("Array with one number [5]: " + Number([5]) + "<br>");
document.write("Array with multiple elements [1,2]: " + Number([1,2]) + "<br>");
document.write("Array with string ['hello']: " + Number(['hello']));
</script>
</body>
</html>
Empty array []: 0 Array with one number [5]: 5 Array with multiple elements [1,2]: NaN Array with string ['hello']: NaN
Key Points
- Empty array
[]converts to0 - Array with single number element converts to that number
- Arrays with multiple elements or non-numeric content convert to
NaN - The conversion uses
toString()internally before converting to number
Conclusion
An empty array [] converts to 0 in JavaScript due to the automatic type coercion process. Understanding this behavior helps avoid unexpected results in numeric operations.
Advertisements
