I'm trying to define a variable in forEach scope like that:
let myVar;
Object.entries(obj).forEach(([key, value]) => myVar = key);
console.log(myVar) // this is undefined, why?
I'm trying to define a variable in forEach scope like that:
let myVar;
Object.entries(obj).forEach(([key, value]) => myVar = key);
console.log(myVar) // this is undefined, why?
First of all, I would avoid that: you're creating side effects that might lead to bugs that would be hard to debug. There are definitely better way to do what you want – e.g. if you want to capture the last keys of an object.
However. The code you wrote works, it would return undefined
depending by the value of obj
. For example:
let myVar;
Object.entries({}).forEach(([key, value]) => myVar = key);
console.log(myVar) // undefined
Where:
let myVar;
Object.entries({foo:1, bar:2}).forEach(([key, value]) => myVar = key);
console.log(myVar) // "bar"