let specificSuffix = function(words, suffix) {
if (!Array.isArray(words)) {
return [];
}
return words.filter(function(word){
return word.endsWith(suffix)
});
}
console.log(specificSuffix(['family', 'hound', 'catalyst', 'fly', 'timidly', 'bond'], 'ly'));
// [ 'family', 'fly', 'timidly' ]
console.log(specificSuffix(['simplicity', 'computer', 'felicity'], 'ily'));
// [ ]
I'm confused specifically about:
return words.filter(function(word) {
return word.endsWith(suffix)
});
}
How am I returning both of these things? The filter is saying, return this empty new array, fill it with the words that endWith the suffix... (I think)
It's really just the two returns that are throwing me. How does this work?
CodePudding user response:
return words.filter(function(word){
return word.endsWith(suffix)
});
The outer return returns the result of words.filter()
. Inside the filter()
function we have to pass a callback. So the return
inside is for that callback. In short you have to return true/false, based on a condition inside the filter callback.
CodePudding user response:
when the indentation of the code is so badly done, it is normal that there is this confusion...
same code with a correct indentaion:
let specificSuffix = function(words, suffix) {
if (!Array.isArray(words)) {
return [];
}
return words.filter( function(word) {
return word.endsWith(suffix)
});
}
Or same code with arrow function
function specificSuffix(words, suffix)
{
if (!Array.isArray(words)) return [];
return words.filter( word => word.endsWith(suffix) )
}
CodePudding user response:
Perhaps if we extract the variable result
the code will make more sense?
const specificSuffix = function(words, suffix) {
if (!Array.isArray(words)) return [];
const result = words.filter(function(word) {
return word.endsWith(suffix)
});
return result;
};