@nhuyvan1106 Good question. In principal, your assumption is correct. In many programming languages, using string concatenation in loops is discouraged and there are dedicated classes to do that (i.e. StringBuilder in C#/Java).
Coming from those languages, I thought I should avoid += in loops, too. However, I just looked it up to be sure and here is what I’ve gathered: Modern JavaScript engines will internally optimize your first approach to behave like the second, so there is no need to do that yourself. [1]
I think one should try to write code that is easy to read for humans, even at the cost of small performance penalties.
If in doubt, you can always do a speed test yourself:
function test() {
Math.sqrt(2);
}
var iterations = 1000000;
time = 0, start, stop;
for (var i = 0; i < iterations; i++) {
start = Date.now();
test();
stop = Date.now();
time += stop - start;
}
console.log('Average time taken: ' + (time / iterations) +
'ms' + '-- total:' + time + 'ms');
Do this for both algorithms and compare the results. If you’re lazy, like me, you can also ask google instead 