In JavaScript:
var stringVar = 12345 + []
Will cast the number to a string.
Small demo: https://jsfiddle.net/ce9bjcwo/
Why does this happen?
In JavaScript:
var stringVar = 12345 + []
Will cast the number to a string.
Small demo: https://jsfiddle.net/ce9bjcwo/
Why does this happen?
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"
It happens because:
There is no way to apply the + operator to an array, so Javascript stringifies the array. Since it's an empty array, it stringifies as ''. Then you have 12345 + ''
And in javascirpt "number" + "string" returns a string, by casting the number to a string and treating + as concatenation operator.
it's due to the fact it is trying to concatenate it to an empty string You may understand it better if you try something like
var stringVar = ""+123;
the amazing thing is that if you do
stringVar = stringVar - 0 ;
it turns to an integer
then if you evaluate
stringVar == '123'
you get true
but if you evaluate
stringVar === '123'
you get false
so cool