Reputation: 4694
Is it safe to assume that "test=" + ['abc', 'xyz']
will produce "test=abc,xyz"
for all JavaScript execution environments that follow standard?
Upvotes: 0
Views: 72
Reputation: 18951
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?
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);
Upvotes: 1
Reputation: 4694
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
.
Upvotes: 2