Alberto Rivera Alberto Rivera - 1 year ago 131
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:

Why does this happen?

Answer Source

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.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download