[javascript] How do I combine 2 javascript variables into a string

I would like to join a js variable together with another to create another variable name... so it would be look like;

for (i=1;i<=2;i++){
    var marker = new google.maps.Marker({
position:"myLatlng"+i,
map: map, 
title:"title"+i,
icon: "image"+i
}); 
}

and later on I have

myLatlng1=xxxxx;
myLatlng2=xxxxx;

This question is related to javascript variables

The answer is


if you want to concatenate the string representation of the values of two variables, use the + sign :

var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1

But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:

function Container(){
   this.variables = [];
}
Container.prototype.addVar = function(var){
   this.variables.push(var);
}
Container.prototype.toString = function(){
   var result = '';
   for(var i in this.variables)
       result += this.variables[i];
   return result;
}

var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1

the advantage is that you can get the string representation of the two variables, bit you can modify them later :

container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3

You can use the JavaScript String concat() Method,

var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"

Its syntax is:

string.concat(string1, string2, ..., stringX)

warning! this does not work with links.

var variable = 'variable', another = 'another';

['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');

ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:

// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);

// => "Yo, Brendan!"

var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);

//=> JavaScript first appeared 20 years ago. Crazy!