0

Is it safe to assume that "test=" + ['abc', 'xyz'] will produce "test=abc,xyz" for all JavaScript execution environments that follow standard?

4
  • Yes it internally uses array.join(',') which just concatenates the strings with , in between them. Result may differ when array elements are non-strings. Commented Jul 3, 2019 at 11:37
  • It depends what you consider "safe". Array#toString can be overridden with your own logic. Commented Jul 3, 2019 at 11:40
  • I wouldn't say so, "standard" has changed and will continue to change. The beauty of JS is that you still can add the 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. Commented Jul 3, 2019 at 11:41
  • Also, xkcd standards, just for the fun Commented Jul 3, 2019 at 11:49

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

2 Comments

If I am paranoid enough to expect that someone overwrite Array.prototype.toString, can I really rely on Array.prototype.join ;-)
Fair point. You can of course make that argument for every methods and functions. Just be aware that it is not unusual to override toString() though, especially when you need some custom serialisation logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.