Answers for "variable name as a string in Javascript function"

2

variable name to string javascript

//Get variable name as string
function getVariableName(v) {
    for (var key in window) {
        if (window[key] === v)
            return key;
    }
}

//testing
var someValue = "something not important right now";
console.log(getVariableName(someValue)); //>> prints "someValue"
//also works in functions
function print(a) {
  console.log(getVariableName(a)); //>> prints "someValue" because of line 16
  //you'd think it would print "a" but it doesnt
}
print(someValue);//>> look at line 14
Posted by: Guest on May-04-2021
2

get variable name javascript

const myFirstName = 'John'
Object.keys({myFirstName})[0]

// returns "myFirstName"
Posted by: Guest on September-09-2020
-1

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");
Posted by: Guest on December-18-2020

Code answers related to "variable name as a string in Javascript function"

Code answers related to "Javascript"

Browse Popular Code Answers by Language