Estoy tratando de agregar 2 a la matriz dada. Pero el código devuelve indefinido cuando se ejecuta. Estoy tratando de aprender ES6, no pude encontrar el problema. Necesito ayuda.
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]));Está registrando undefined porque la función no devuelve ningún valor.
Tienes que devolver el resultado de 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])); También tenga en cuenta que la declaración de return en su función de flecha es redundante, ya que solo se evalúa una expresión:
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]));No tiene una declaración de return en la función, por lo que devuelve undefined de forma predeterminada.
Si una función de flecha es una sola expresión que desea devolver, no debe poner {} alrededor de ella. Eso lo convierte en un cuerpo de función normal, que requiere una declaración de return explícita (como la que tiene con 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