3

I saw this example and wondered why anyone would do it:

function a(str) {
  return [
    '<div>',
     str,
    '</div>'
  ].join('');
}

Isn't it an equivalent to the following code and what's the advantages / disadvantages of using just:

function a(str) {
  return '<div>' +
     str +
    '</div>;
}

Thank you.

nicael
  • 18,550
  • 13
  • 57
  • 90
Fijir
  • 217
  • 4
  • 9
  • 1
    They're equivalent... Also, you can just test it, no? – nicael Jan 08 '16 at 20:39
  • @nicael, I understand. But what is better? – Fijir Jan 08 '16 at 20:39
  • In you particular example, it doesn't matter, really. The second is just obviously shorter, and the first is an excess complication for this problem. – nicael Jan 08 '16 at 20:40
  • 1
    @nicael, I think string is more faster, for example – Fijir Jan 08 '16 at 20:41
  • So you know which is better and why, what is the reason behind your question then? – nicael Jan 08 '16 at 20:42
  • 1
    In this particular example, I prefer the second way, because it is easier to understand. In the first function, you see "return [" so you initially think it's returning a list. Only after you get to the end of the function you find the ".join('')" which turns it into a string. In the second example, the code is easier to parse for humans. – Adi Levin Jan 08 '16 at 20:42
  • 1
    In old days, things like that mattered when building large strings. In modern browsers it is a personal style preference. – epascarello Jan 08 '16 at 20:44
  • @nicael, I'm asking because maybe I don't understand everything. I saw this example and I was surprised. – Fijir Jan 08 '16 at 20:44

2 Answers2

2

They're the same thing. Some experiments have shown using the + operator is faster but this will vary between browsers. Not to mention, these kinds of micro-optimizations don't tend to contribute much.

So which one is better? Whichever one you like the most.

Community
  • 1
  • 1
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

My preference would be to use the "string concatenation" version, in other words, your second one.

They both return the same thing. In the case of the first example however your combining string elements of an array together. In the second one, you're simply adding the strings together.

There's no need to use an array to solve this problem, and the second one is much more concise too. It's a better web development practice.

Performance wise, there will be a slight improvement with the second one. Since it has less space, that means the JavaScript file that loads it will be smaller, taking up fewer resources on a user's browser.

It will also make it more easily maintainable with fewer lines of code.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87