Useful JS Tips

#19 - Safe string concatenation

2016-01-19 by @gogainda

Suppose you have a couple of variables with unknown types and you want to concatenate them in a string. To be sure that the arithmetical operation is not be applied during concatenation, use concat:

var one = 1;
var two = 2;
var three = '3';

var result = ''.concat(one, two, three); //"123"

This way of concatenting does exactly what you’d expect. In contrast, concatenation with pluses might lead to unexpected results:

var one = 1;
var two = 2;
var three = '3';

var result = one + two + three; //"33" instead of "123"

Speaking about performance, compared to the join type of concatenation, the speed of concat is pretty much the same.

You can read more about the concat function on MDN page.

<<返回目录