user6008337 user6008337 - 4 months ago 6
Javascript Question

how to call a function as argument in javascript

I am learning javascript, i was wondering if it was possible to have something like this use of lambda function

function operation (function f, num1, num2){
f.call(num1, num2);
}
operation((a,b)=>{return a+b}, 2,3);


I have Unexpected token function at line 1, for function f i imagine, is there a way to make this work somehow ?

Answer

Try this:

function operation (f, num1, num2){
    f(num1, num2);
}
operation((a,b)=>{return a+b}, 2,3);

JavaScript is untyped language. If you want to use call, try this:

function operation (f, num1, num2){
    f.call(this, num1, num2);
}
operation((a,b)=>{return a+b}, 2,3);
Comments