Reputation: 63
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(' ');
}
Upvotes: 0
Views: 43
Reputation: 3761
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.
Upvotes: 2
Reputation: 370679
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.log
ged.
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
function
keyword, rather than an arrow function, and thus needs the return
keyword in order to return values (unlike arrow functions in some circumstances).Upvotes: 2