What’s the best way to do string building/concatenation in JavaScript?

With ES6, you can use

ES5 and below:

  • use the + operator

    var username="craig";
    var joined = 'hello ' + username;
    
  • String’s concat(..)

    var username="craig";
    var joined = 'hello '.concat(username);
    

Alternatively, use Array methods:

  • join(..):

    var username="craig";
    var joined = ['hello', username].join(' ');
    
  • Or even fancier, reduce(..) combined with any of the above:

    var a = ['hello', 'world', 'and', 'the', 'milky', 'way'];
    var b = a.reduce(function(pre, next) {
      return pre + ' ' + next;
    });
    console.log(b); // hello world and the milky way
    

Leave a Comment