I want to compare each string in an Array with a given string. My current implementation is:
function startsWith(element) {
return element.indexOf(wordToCompare) === 0;
}
addressBook.filter(startsWith);
This simple function works, but only because right now wordToCompare is being set as a global variable, but of course I want to avoid this and pass it as a parameter. My problem is that I am not sure how to define startsWith() so it accepts one extra parameter, because I dont really understand how the default parameters it takes are passed. I’ve tried all the different ways I can think of and none of them work.
If you could also explain how the passed parameters to ‘built in’ callback functions (sorry, I dont know of a better term for these) work that would be great
Make
startsWithaccept the word to compare against and return a function which will then be used as filter/callback function:Another option would be to use
Function.prototype.bind[MDN] (only available in browser supporting ECMAScript 5, follow a link for a shim for older browsers) and “fix” the first argument:There is nothing special about it. At some point,
filterjust calls the callback and passes the current element of the array. So it’s a function calling another function, in this case the callback you pass as argument.Here is an example of a similar function: