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?
1
  • 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. Commented Aug 22, 2019 at 23:22

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.