1

Let say you have a for loop and you want to build a string in a very specific way using template literals

I've find 2 similar ways to do it.

let text = ''
words = ['Hello', 'world']
for (i = 0; i < n; i++) {
    text += `${words[i]} || `
}

Or

let text = ''
words = ['Hello', 'world']
for (i = 0; i < n; i++) {
    text = `${text}${words[i]} || `
}

Both produce the same output (Hello || world || )

Is any difference in performance or standard?

5
  • 1
    You can compare performance at jsperf.com Commented Nov 6, 2018 at 18:15
  • 1
    Add this ['Hello', 'world'].concat('').join(" || ") as a task to measure performance. Commented Nov 6, 2018 at 18:16
  • Another performance comparer: jsben.ch/FskS4 Commented Nov 6, 2018 at 18:17
  • 2
    "Which is more efficient" questions often don't age well. Joining arrays instead of repeated string concatenation used to be the right answer, but then browser venders optimized the latter, making that more efficient. The answer will be different from JS engine to JS engine. Commented Nov 6, 2018 at 18:19
  • Thank you very much for your comments and help! Commented Nov 6, 2018 at 19:03

1 Answer 1

1

I would use words.join(" || ")+" || " today is the fastest way, see this http://jsben.ch/DlXOa , as @jacob points out, it is a relative conclusion. But, as a general rule in JavaScript, usually built-in methods are faster.

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

Comments

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.