Wednesday, October 12, 2011

Javascript string concatenation vs array.join()

When we are implementing some dynamic web contents, most of the time, We have used to create string HTML and set it as an inner HTML of particular container elements. Normally, We use '+' operator to concatenate strings as follows.

var html = "<table><tr><td>";
html += "This is td contents";
html += "</td></tr></table>";

I will suggest you a more faster method to do the same. For this, I am going to keep every string as an element of javascript array and finally join them to create a one string.

var sb = []; //create empty javascript array
sb[sb.length] = "<table><tr><td>";
sb[sb.length] = "This is td contents";
sb[sb.length] = "</td></tr></table>";
Now By simply  concatenating them all together with a separator between them, You can get a one string as follows.The default separator is ','. To join without separation, use an empty string as the separator.
var html = sb.join("");

If you are assembling a string from a large number of pieces, it is usually faster to put the pieces into an array and join them than it is to concatenate the pieces with the + operator.


Post a Comment