Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
Not understanding the second return statement in this function

I am learning javascript and while I was on Codewars I couldn't figure this problem out so I looked for a solution.

This is the solution I found and I just don't understand why there needs to be a second return statement inside the map method. If anyone could give me some insight it would be much appreciated. Thank you.

let spinWords = (str) => {
    return str.split(' ').map(function(string) {
        return (string.length > 4) ? string.split('').reverse().join('') : string 
    }).join(' ');
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The .map function accepts a callback, and that callback is a function that runs for every item in the array. For a simple example:

const upperCase = str => str.toUpperCase();

console.log(
  ['a', 'b'].map(upperCase)
);

Above, it's called with both elements of the array: upperCase('a') and upperCase('b'), and the results are put into the new array, which is then console.logged.

You can also define functions inline and pass that to .map:

console.log(
  ['a', 'b'].map(str => str.toUpperCase())
);

Your code's original

str.split(' ').map(function(string) {
   return (string.length > 4) ? string.split('').reverse().join('') : string 
}).join(' ');

is doing the same sort of thing, except that

  • the body of the function is more complicated, and
  • it's using the function keyword, rather than an arrow function, and thus needs the return keyword in order to return values (unlike arrow functions in some circumstances).
about 4 years ago · Juan Pablo Isaza Denunciar

0

The second return is a callback function. Try looking at it like this:

function reverseWord(string) {
   return (string.length > 4) ? string.split('').reverse().join('') : string 
  }
let spinWords = (str) => {
    return str.split(' ').map(reverseWord).join(' ');
}

So reverseWord is your callback function, with its own return. The value it returns is the value used in the mapped array.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda