Home > OS >  I can't understand why it returns undefined
I can't understand why it returns undefined

Time:09-25

I am trying to add 2 to given array. But the code returns undefined when run. I am trying to learn ES6, I couldn't find the problem. I need help.

const mapSomething = (arr) => {
  arr.map(n => {
    return n   2;
    
  })
}

// It have to return [3, 4, 5] but it returns undefined
console.log(mapSomething([1, 2, 3]));

CodePudding user response:

It is returning undefined because the function is not returning any value.

You have to return the result from Array.map:

const mapSomething = (arr) => {
  return arr.map(n => {
    return n   2;
  })
}

// It have to return [3, 4, 5] but it returns undefined
console.log(mapSomething([1, 2, 3]));

CodePudding user response:

You don't have a return statement in the function, so it returns undefined by default.

If an arrow function is a single expression that you want to return, you shouldn't put {} around it. That makes it a normal function body, which requires an explicit return statement.

const mapSomething = (arr) => arr.map(n => n   2);

// It have to return [3, 4, 5] but it returns undefined
console.log(mapSomething([1, 2, 3]));

  • Related