1

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.

Umbungu
  • 945
  • 3
  • 10
  • 30

2 Answers2

2

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
}
c.P.u1
  • 16,664
  • 6
  • 46
  • 41
  • So there is no security issue in doing this? – Umbungu May 21 '13 at 09:29
  • 1
    @Mewzer just remember to leave off the parenthesis `()` when you pass a function as a parameter as you are just passing the function reference into the new function and not calling it – Mark Walters May 21 '13 at 09:30
1

I can say it's very common in js, you can see usage as in apply and call

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

What is the difference between call and apply?

but it may impose security risks if the function (param2) is passed two you from user or third-party that you do not trust (eg. you offer some server like widget to third-parties)

Community
  • 1
  • 1
Muayyad Alsadi
  • 1,506
  • 15
  • 23