0

I want to get a boolean from an Object.entries(b).foreach but I don't know how to retrieve it.

Like :

const body = {a:1,b:2}
function handle() {
  let myBool = true;
  Object.entries(body).forEach(([key, value]) => {
   myBool = false;
  });
  return myBool;
}

So, that's always return true, I tried something like

const body = {a:1,b:2}
function handle() {
  return Object.entries(body).forEach(([key, value]) => {
   return false;
  });
}

But it doesn't work. it's probably a lack of understanding JS, can you give me a hint ?

  • 4
    I tried your first piece of code and it does return false as expected. What's the issue there? – Emilien Dec 28 '22 at 07:57
  • 1
    See [What does `return` keyword mean inside `forEach` function?](/q/34653612/4642212). – Sebastian Simon Dec 28 '22 at 07:58
  • 2
    return Object.entries(body).forEach(...) doesn't make sense since forEach always returns undefined. If you want to return something, for example an array of booleans, use map instead. – Emilien Dec 28 '22 at 08:00

1 Answers1

1

Unlike Array.prototype.map(), Array.prototype.forEach() always returns undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

More details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

DreamBold
  • 2,727
  • 1
  • 9
  • 24