Wednesday, 11 September 2013

Make strings with join() or addition?

Make strings with join() or addition?

I ran into a bit of code that I found interesting, and I am not sure why
the coding pattern is used. Perhaps someone could enlighten me?
In the example bellow, an Array and join() is used to create a string of
html then inserted into a DIV-element with innerHTML.
var div = document.createElement('div');
div.id = 'test';
div.innerHTML = [
'<div id="create-account-view">',
'<button class="cancel">cancel</button>',
'<ul id="create-account-presets"></ul>',
'</div>'
].join('');
document.body.appendChild(div);
Why would one do this? Why not make a String as shown bellow.
var div = document.createElement('div');
div.id = 'test';
div.innerHTML =
'<div id="create-account-view">' +
'<button class="cancel">cancel</button>' +
'<ul id="create-account-presets"></ul>' +
'</div>';
document.body.appendChild(div);
I ran a jsperf.com test, and first example is much slower, so why use it?
Are there any other aspects I am missing?

No comments:

Post a Comment