Skip to content Skip to sidebar Skip to footer

Curious Behavior Of String()

I was just messing around with some code today, and I noticed that when I run String(null) or String(undefined), I get null and undefined respectively. But, when I checked the valu

Solution 1:

String(x) calls x.toString().

null and undefined values are represented by empty strings by Arrays' toString() since it calls Array.prototype.join() ("If element is undefined or null, let next be the empty String"):

> [null, undefined].toString()
","
> [null, null, null, null].toString()
",,,"

Solution 2:

You can use:

String([null, undefined].map(String));

or

[null, undefined].map(String).join()

Post a Comment for "Curious Behavior Of String()"