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]));
It is logging 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]));
Also take note that the return statement in your arrow function is redundant, since there is only one expression being evaluated:
const mapSomething = (arr) => {
return arr.map(n => n + 2)
}
// It have to return [3, 4, 5] but it returns undefined
console.log(mapSomething([1, 2, 3]));
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 (like you have with n + 2).
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]));
const mapSomething = (arr) => {
const arrData = arr.map(n => {
return n + 2;
})
return arrData
}
// It have to return [3, 4, 5] but it returns undefined
console.log(mapSomething([1, 2, 3]))
//NOTE: you where not returning anything from the function itself