How do we create a function that takes a callback as the first parameter

Hi guys,

I would like to create a function that can take a callback function as the first parameter, so other parameters can be passed to that callback function. A good example is if we look at how the array.forEach method is set up, how can we mimic this? (seen on MDN array.forEach)

arr.forEach(function callback(currentValue[, index[, array]]) {}

Notice how the callback function takes the parameters that are sent to the forEach method? When I try to write it all i can get to work is the following and i cannot pass the callback any parameters unless I do it in the myFunc function, which is redundant

function myFunc(value1, value2, callback) {}

Any help is appreciated

The general approach of callbacks are that they are invoked in the end of the function when the general functionality is done.

function doSomething(callback) {
    // Do your stuff here

    // Call the callback
    callback('stuff', 'goes', 'here');
}

function foo(a, b, c) {
    // I'm the callbackfunction!
    alert(a + " " + b + " " + c);
}

// Invoke doSomething and pass in foo as argument
doSomething(foo);

Hi Ronnehag,

I appreciate your reply to the thread!

For anyone who had trouble figuring this out and how to do it practically please see my example below. I used it for a calculator function example, it would take the same variables with a different callback function to return different result.

function calc(callback){
console.log(callback);
}
function add(a,b){
return a+b;
}
function subtract(a,b){
return a-b;
}

calc(subtract(143,356));

Thanks!