0

I am making a program in node.js (JavaScript) and i want it to make an array with the name that is in a variable, So something like this

const name = "test"
const name = ["Contents", "Here"]; // Trying to make an array called the name 
// stored in the "name" variable

Thanks!

houseofkraft
  • 191
  • 1
  • 2
  • 8

2 Answers2

1

You could do this with a property name in an object. But, AFAIK, you'd need something like an eval() to do it with an array (and you shouldn't use eval()).

Here's how it would go with an object:

var myObject = {};
const name = "test"
myObject[name] = ["Contents", "Here"]; 

// Test
console.log(myObject.test);
console.log(myObject[name]);
console.log("Does object have a 'test' property? " + (name in myObject && name === "test"));
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Why not make `myObject` const, too? – melpomene Dec 04 '16 at 22:43
  • @melpomene Just a quick example using OPs code. Doesn't really affect the answer. – Scott Marcus Dec 04 '16 at 22:44
  • @melpomene—why make *name* a *const* at all? – RobG Dec 04 '16 at 22:46
  • @RobG Because everything should be as const as possible. Only marking variables as `var` (or better `let`) if you want to modify them later helps avoiding bugs. – melpomene Dec 04 '16 at 22:47
  • @melpomene Well, that's an opinion that has merit. But, a case could be made for the opposite. Regardless, you can't expect all answers on SO to be 100% perfect in every regard when certain conventions are not relevant to the answer. – Scott Marcus Dec 04 '16 at 22:50
  • @melpomene—I have never had a bug that would have been avoided by using *const* instead of *var*, but that's just my limited experience. The OP has a bug *caused* by *const* (thought it is likely only pseudo code). ;-) – RobG Dec 05 '16 at 04:15
-1
const var_name = "test"
const arr_name.push(var_name);
console.log(arr_name)?

I don't be sure that This code will meet your demand.

GyeJin Lee
  • 24
  • 5