agente_secreto agente_secreto - 9 months ago 42
Javascript Question

How do I pass an extra parameter to the callback function in Javascript .filter() method?

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;

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 startsWith accept the word to compare against and return a function which will then be used as filter/callback function:

function startsWith(wordToCompare) {
    return function(element) {
        return element.indexOf(wordToCompare) === 0;


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:

function startsWith(wordToCompare, element) {
    return element.indexOf(wordToCompare) === 0;

addressBook.filter(startsWith.bind(this, wordToCompare));

I dont really understand how the default parameters it takes are passed

There is nothing special about it. At some point, filter just 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:

function filter(array, callback) {
    var result = [];
    for(var i = 0, l = array.length; i < l; i++) {
        if(callback(array[i])) {  // here callback is called with the current element
    return result;