Is it safe to assume that "test=" + ['abc', 'xyz'] will produce "test=abc,xyz" for all JavaScript execution environments that follow standard?
2 Answers
After taking a look at the ECMAScript 2015 Language Specification I could confirm the expected behaviour, as long as toString is not overwritten:
ToString will be evaluated with ToPrimitive which in turn evaluates OrdinaryToPrimitive for the Array with the hint set to string which then finally calles the Arrays toString.
Comments
It might be safe 99% of the time but since it is JavaScript you should also expect monkey patching.
Even if you run in a safe environment, I would still opt for clarity:
const arr = ['abc', 'xyz'];
const str = `test=${arr.join(',')}`;
Why?
- The intent is clearer (IMHO)
- People who don't know the inner workings of JavaScript can still understand that code
What's up with the 1%?
People can and will monkey patch JavaScript. Can you afford a risk there?
Array.prototype.toString = () => '🌯🌯🌯';
const arr = ['abc', 'xyz'];
const str = 'test=' + arr;
console.log(str);
2 Comments
Array.prototype.toString, can I really rely on Array.prototype.join ;-)toString() though, especially when you need some custom serialisation logic.
array.join(',')which just concatenates the strings with,in between them. Result may differ when array elements are non-strings.Array#toStringcan be overridden with your own logic.toString()method as a shim for ol' environments. Note that your standard will change, you should precise it in the question so that it can last in time.