Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!