Rabios
Rabios

Reputation: 77

Print correct variable name in JavaScript

I'm trying to log variable name in JavaScript with its value using a function with the following code...

var x = 5;
function get(v) {
    console.log(Object.keys({v})[0] + " = " + v);
}
get(x); // It should log "x = 5"

But instead, it logs v = 5.

Is there a way to store the variable name, and to log the variable name correctly?

Upvotes: 0

Views: 43

Answers (1)

trincot
trincot

Reputation: 350310

That happens because at the time you print, you are constructing an object which has a key named "v"... that is what {v} does.

You can solve this by creating the object at the moment that you have access to the x variable, and do {x}:

var x = 5;
function get(v) {
    console.log(Object.entries(v)[0].join(" = "));
}
get({x});

Upvotes: 3

Related Questions