# Passing functions as parameters in JavaScript

Functions, like numbers, strings, and arrays, can be passed as parameters to other functions.

Let's take a closer look at a practical example. Let's say we have the function `test` that takes two parameters:

`test(parameter1, parameter2);`

Let's pass an anonymous function that returns `1` to the first parameter of the `test` function, and an anonymous function that returns `2` to the second parameter:

`test( function() {return 1;}, function() {return 2;} );`

The code above is not working yet because we haven't created the function itself. Let's do it:

`function test(func1, func2) { }`

When defining the function, we specified two parameters - `func1` and `func2`. These parameters don't know anything about what will be transmitted in them. We can, for example, pass numbers:

`test(1, 2); // call the function function test(func1, func2) { console.log(func1); // shows 1 console.log(func2); // shows 2 }`

ALso we can pass the functions:

`test( function() {return 1;}, // first parameter function() {return 2;} // second parameter ); function test(func1, func2) { console.log(func1); // shows 'function() {return 1;}' console.log(func2); // shows 'function() {return 2;}' }`

As you can see, the source code of the functions is now printed to the console. Let's make it output their results. To do this, we write parentheses to the functions:

`test( function() {return 1;}, function() {return 2;} ); function test(func1, func2) { console.log( func1() ); // shows 1 console.log( func2() ); // shows 2 }`

Let's print the sum of the results of the first and second function to the console:

`test( function() {return 1;}, function() {return 2;} ); function test(func1, func2) { console.log( func1() + func2() ); // shows 3 }`

Make the function `test` that takes `3` functions as parameters. Pass in the first parameter a function that returns `1`, the second - a function that returns `2`, the third - a function that returns `3`. Print the sum of the results of the functions to the console.

←→
↑
en ru