Jordan
Jordan

Reputation: 51

Passing blocks of code to functions/function pointers JavaScript

I have a function that has a couple of for statements in it. I need to be able to pass code to the for statements via parameters.

var a = function(paramCode){
    for(var eachRow=0; eachRow<20; eachRow++){
        for(var eachCol=0; eachCol<20; eachCol++){
            paramCode
        }
    }
}

a({ //the code I want to pass is surrounded in the function pointers
    if(array[x][y]){
        //do something
    }
});

This is a basic version of what I'm trying to do. The only problem is the error I get in the console.

Uncaught SyntaxError: Unexpected token [

I would love to know how to fix this error, or a way that I can still do what I'm trying to do.

Upvotes: 1

Views: 192

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You could create a callback, this is a function which is handed over to the calling function as parameter.

var a = function (callback) {
        for (var eachRow = 0; eachRow < 20; eachRow++) {
            for (var eachCol = 0; eachCol < 20; eachCol++) {
                callback(array, eachRow, eachCol);
            }
        }
    };

a(function (array, x, y) {
    if (array[x][y]){
        //do something
    }
});

Upvotes: 4

Related Questions