Nick Russler
Nick Russler

Reputation: 4694

How is concatenation with the plus operator defined for String plus Array in JavaScript

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

Answers (2)

customcommander
customcommander

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?

  1. The intent is clearer (IMHO)
  2. 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);

Upvotes: 1

Nick Russler
Nick Russler

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:

Screenshot from Spec

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

Related Questions