Alberto Rivera Alberto Rivera - 1 month ago 5
Javascript Question

Casting a number to a string by adding an array in JavaScript

In JavaScript:

var stringVar = 12345 + []


Will cast the number to a string.

Small demo: https://jsfiddle.net/ce9bjcwo/

Why does this happen?

Answer

Due to Array.prototype.toString().
It converts it to a string representation when trying to concatenate, and since 12345 is not a string, it's type-cast to one.

Examples:
[1,2].toString() -> "1,2"
[].toString() -> ""
12345 + "" -> "12345"

Comments