1

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?
Murakami
  • 3,474
  • 7
  • 35
  • 89
  • 1
    What is the desired behaviour? With that code you are assigning the last key in the obj (in case it have any) to myVar. When your object *obj* does not have any key nothing happens, like {}, that's why myVar remains undefined. – Rigoberto Ramirez Cruz Aug 22 '19 at 23:22

1 Answers1

1

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"
ZER0
  • 24,846
  • 5
  • 51
  • 54