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:

  1. First, it calls the valueOf() method on the array, which returns the array itself
  2. Since the result isn't a primitive, it calls toString() on the array
  3. An empty array's toString() returns an empty string ""
  4. 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 to 0
  • 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.

Updated on: 2026-03-15T23:18:59+05:30

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements