javascriptjavascript-security

Security: Passing a function as a parameter in JavaScript


I am very very new to JavaScript, so please bear with me!.

I was wondering if you pass a function as a parameter to another function in JavaScript, for example (disclaimer: the code may not be 100% correct, but you should get the idea!):

function(param1, param2) {

   ....
   // Do something with param 1
   param1 += 10;
   ....

   // Param 2 is a function, so call it
   param2();

   .....
}

Is this a potential security risk, or is this a common way of programming in JavaScript?.

Thanks.


Solution

  • In JavaScript, functions are first class citizens. You can assign a function to a var, pass functions as arguments to other functions or return a function as a result from another function.

    There are many methods in JavaScript that accept a function as an argument(also called callback functions). One such example is forEach

    Array.prototype.forEach();
    
    var elements = [42, 33, 45, 5];
    
    elements.forEach(/*anonymous function*/function(element, index) {
    // do something with element
    });
    
    elements.forEach(callback);
    
    function callback(element, index) {
    //do something with element
    }