What is the correct way to concatenate strings in JavaScript?

4

I started learning Python and was told I should not concatenate the strings with , but use the .format() method. And in JavaScript is it correct to use + or , to concatenate strings or is there a more recommended and most used way?

    
asked by anonymous 23.08.2017 / 01:18

3 answers

1

You can also use "template string" for this:

var str1 = 'hello';
var str2 = 'world';
var res = '${str1} ${str2}';

In this case where there are only 2 strings, it does not make much sense to use, but in larger concatenations, it's very interesting.

Template string is part of ES6 / ES2015, some older browsers may not support.

link link

    
23.08.2017 / 18:52
6

There's nothing ugly or wrong about making a simple str1+" "+str2 . You can use it without problems. It is simple and efficient. There's no technical reason to choose a shape, it's just a style.

Although ugly depends on taste, I find any other ugly, longer and even less intuitive way when it hits the eye fast. Choose one and be consistent, do not keep changing form.

There could be problems if you make too many concatenations within a loop, but even this JS optimizes, so even using str += str2 is fitting in a loop.

    
23.08.2017 / 01:29
2
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2);

Result: Hello world!

Reference: link

Another way, with + :

var res = str1+str2;
    
23.08.2017 / 01:19