0

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?

0

1 Answer 1

3

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});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.