Writing Html using javascript

1

I was studying some jquery plugins and realized that to create the html, the programmer wrote each line in an array and finally used the join:

var tpl = [
		'<div class="popover clockpicker-popover">',
			'<div class="arrow"></div>',
			'<div class="popover-title">',
				'<span class="clockpicker-span-hours text-primary"></span>',
				' : ',
				'<span class="clockpicker-span-minutes"></span>',
				'<span class="clockpicker-span-am-pm"></span>',
			'</div>',
			'<div class="popover-content">',
				'<div class="clockpicker-plate">',
					'<div class="clockpicker-canvas"></div>',
					'<div class="clockpicker-dial clockpicker-hours"></div>',
					'<div class="clockpicker-dial clockpicker-minutes clockpicker-dial-out"></div>',
				'</div>',
				'<span class="clockpicker-am-pm-block">',
				'</span>',
			'</div>',
		'</div>'
	].join('');

Someone with experience knows why to write that way, ie without using a string and concatenating each line?

var tpl = '<div class="popover clockpicker-popover">'+
			'<div class="arrow"></div>'+
			'<div class="popover-title">'+
				'<span class="clockpicker-span-hours text-primary"></span>'+
				' : '+
				'<span class="clockpicker-span-minutes"></span>'+
				'<span class="clockpicker-span-am-pm"></span>'+
			'</div>'+
			'<div class="popover-content">'+
				'<div class="clockpicker-plate">'+
					'<div class="clockpicker-canvas"></div>'+
					'<div class="clockpicker-dial clockpicker-hours"></div>'+
					'<div class="clockpicker-dial clockpicker-minutes clockpicker-dial-out"></div>'+
				'</div>'+
				'<span class="clockpicker-am-pm-block">'+
				'</span>'+
			'</div>'+
		'</div>';
    
asked by anonymous 20.06.2017 / 19:11

1 answer

1

When using join or concatenation, concatenating performs better, but writing code can be more cumbersome, especially when using ' with " and when there are many lines.

In this test, locally, the concatenation ran 12,497 times in < in> 0.083 seconds versus 11,144 in 0.087 seconds with join .

In , locally, the concatenation ran 12703 times in 0.086 seconds against 12,875 in 0.080 seconds with Template strings .

Particularly I prefer to use template string when I need to write HTML in javascript. Subjectively it looks better and easier to read, just for multi-line and string strings containing ' and " . And the most interesting about it are Tagged template , which gives this power:

let conta = {numero: '9999-9'};   
tag 'Minha conta é ${conta.numero}.'

Browser Compatibility

    
20.06.2017 / 19:47