javascript create variable name from string code example
Example 1: variable name to string javascript
function getVariableName(v) {
for (var key in window) {
if (window[key] === v)
return key;
}
}
var someValue = "something not important right now";
console.log(getVariableName(someValue));
function print(a) {
console.log(getVariableName(a));
}
print(someValue);
Example 2: how to name a javascript variable
var change_this = 'whatever you want here'
Example 3: how i can add dynamic value in string in javascript
const poem = "The Wide Ocean";
const author = "Pablo Neruda";
const favePoem = `My favorite poem is ${poem} by ${author}.`;
Example 4: variable name as a string in Javascript function
var a = [1, 3, 4, 3]
var b = [1, 5, 6, 7]
var c = [3, 4, 8, 9]
function arraySum(x, varName) {
var sum = 0
for (let i = 0; i < x.length; i++) {
sum += x[i]
}
console.log("sum of " + varName + " is " + sum)
}
arraySum(a, "a");