Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda