'How I could use template literals in javascript in a variable name?
I want to declare a variable name via template literals How it is possible ?
let z = 3;
let test`${z}` = "hello"; //or = new obj() for example
console.log(test3);
Solution 1:[1]
Reference: Template literals
It is not possible. Template literals are used for strings
only.
It is same as: var 'string_var' = 'myval'
// Not accepted.
But, you can do it for object properties.
Such as:
let z = 3;
let obj = {}
obj[`test${z}`] = "hello"
console.log(obj.test3);
Solution 2:[2]
Yes, is possible. This is my code, referencing: Can you use template literal for function name in javascript?
for (i = 1; i < 10; i++) {
global[`list_${i}`] = require(`./LP_${i}_Top_Holder.json`);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Eric Chung |