Alberto Rivera Alberto Rivera - 1 year ago 70
Javascript Question

Casting a number to a string by adding an array on Javascript

In Javascript:

var stringVar = 12345 + []

will cast the number into 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