Maria Jane Maria Jane - 1 month ago 12
Javascript Question

unexpected token when building array of object using variable

Just feel strange why this will throw an error

var a = 'a';
var b = 'b';
const array = [{
a + "&" + b
}, ];

console.log(array)


https://jsfiddle.net/1qcjwwdn/

What I expect is just array
[{'a&b'}];
where a and b is variable.

Answer

you must name your object in array:

var a = 'a';
var b = 'b';
const array = [{objName: a + "&" + b}];