0

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(' ');
}
simo54
  • 218
  • 5
  • 16
ddowy
  • 33
  • 5
  • 2
    `.map()` is used to transform an array by passing source elements into a function and using the **returned** values from that function to build a new array. The "inner" `return` is for that `.map()` callback. – Pointy Nov 04 '21 at 20:35
  • 1
    Please check the docs first: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#parameters (the second return returns from the anonymous inner function that is passed as first argument to the `map()` call) Here's a refactored version with the inner function moved outside: https://jsfiddle.net/x8fkydqw/ –  Nov 04 '21 at 20:36

2 Answers2

2

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).
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

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.

Snowmonkey
  • 3,716
  • 1
  • 16
  • 16