Concatination vs joining with empty string

126 Views Asked by At

In JavaScript, when joining "many" strings together, is it more idiomatic to use the concatenation operator (+), to box as an array then join, or to do something else entirely?

For example:

var a = '1', b = '3', c = '3', d = '7';

a + b + c + d          // => "1337"
// VS 
[a, b, c, d].join('')  // => "1337
// VS
// ... something else?
1

There are 1 best solutions below

3
On BEST ANSWER

In the first case, when you do as a string, the data types here are only strings. Manipulations among the strings are easier, keeping the same data type in case of this:

a + b + c + d

But when you concatenate the string by converting it into an array and then using a join() function, it is a tedious task. You are allocating a new memory space to create an array of these strings, then you are applying a join() function on them, which surely has a performance drop over the native string function with the native operator.

[a, b, c, d].join('')

I am not saying that the array functions are not native, but that you are converting them from one form to another and then applying other actions on it, which makes it more complex.

Also I would like to add the comment by plalx that in some browsers, the join() function is significantly faster. So it also depends on the browser.