- Javascript pass function with parameter
- How to do that?
- The example problem
- The problem with that approach
- Better code with passing function as argument
- But that is not enough
- References
- First Class Functions
- Our Example
- What’s the use?
- Conclusion
- Pass JavaScript Function as Parameter
- Pass a General JavaScript Function as a Parameter
- Pass Both Function and Value to a JavaScript Function
- Related Article — JavaScript Function
- Related Article — JavaScript Parameter
Javascript pass function with parameter
Javascript allows you to pass functions as parameter to another function and that makes Javascript super awesome!. Great things can be achieved from this power.
Quote from Mozilla developer website:
In JavaScript, functions are first-class objects, i.e. they are objects and can be manipulated and passed around just like any other object.
Every Javascript function is a Function object. Hence we can pass them as arguments, like any other object.
How to do that?
Passing function as parameter is no different from passing any other object when it comes to syntax.
I am gonna try and explain that with an example (hopefully, easy to understand)
The example problem
Bob wants to get sum of values [1, 2, 3, 4, 5, 6, 7, 8, 9]
So we give him the following solution
// find sum of values var total = function(values) < var sum = 0; values.forEach( function(value) < sum += value; >); return sum; >;
Bob is happy with the function. But now he wants to get sum of all even numbers in the list of values.
So we copy-paste the above function, rename it and make slight changes.
// find sum of values var total = function(values) < var sum = 0; values.forEach( function(value) < sum += value; >); return sum; >; // find sum of even numbers in list of values var totalEven = function(values) < var sum = 0; values.forEach( function(value) < if( value % 2 === 0 ) sum += value; >); return sum; >;
Bob is happy again. But he wants more. Now he need sum of all odd numbers from the same list.
As usual, we copy-paste, rename and make slight changes.
// find sum of values var total = function(values) < var sum = 0; values.forEach( function(value) < sum += value; >); return sum; >; // find sum of even numbers in list of values var totalEven = function(values) < var sum = 0; values.forEach( function(value) < if( value % 2 === 0 ) sum += value; >); return sum; >; // find sum of odd numbers in list of values var totalOdd = function(values) < var sum = 0; values.forEach( function(value) < if( value % 2 !== 0 ) sum += value; >); return sum; >;
The problem with that approach
- Lot of duplicate code.
- Cluttered and ugly source code.
- Source file becomes unnecessarily lengthy.
- Not applying re-usabilty principle.
- Have to create separate function for each additional request.
Better code with passing function as argument
We can improve the above code a lot by passing the selection functionality as argument. In the above example, the basic operation is summation. Then, we need some kind of selection of values to sum. This selection can be anything, like even numbers, odd numbers etc. This is what we will pass an argument.
var totalSelectValues = function(values, selector) < var sum = 0; values.forEach(function(value) < if(selector(value)) sum += value; >); return sum; >;
The selector , is function passed as parameter. Here we are expecting it to return a boolean value.
var values = [1,2,3,4,5,6,7,8,9]; // even numbers totalSelectValues(values, function(value) < return value % 2 === 0>); // odd numbers totalSelectValues(values, function(value) < return value % 2 !== 0>); // greater than 5 totalSelectValues(values, function(value) < return value >5 >);
Awesome! We just created functions on the fly and passed it as parameters, didn’t even bother to name it! Neat eh? Also we have reduced the code base by far. Just a single function and no ugly repetition.
But that is not enough
We also need to make sure our little function works perfectly even if the second argument is not send.
var totalSelectValues = function(values, selector) < // handle undefined selector if (typeof selector == 'undefined' ) < selector = function() ; > var sum = 0; values.forEach(function(value) < if(selector(value)) sum += value; >); return sum; >;
The complete example is available in the following jsFiddle. http://jsfiddle.net/deepumohanp/s2DBJ/
References
- I got the example inspiration from Dr. Venkat Subramaniam’s talk an Scala.
- http://www.youtube.com/watch?v=LH75sJAR0hc
- https://vimeo.com/57988159
- http://www.joelonsoftware.com/items/2006/08/01.html
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
First Class Functions
In JavaScript, functions are considered «first class» or «higher order» functions. This is basically just a fancy way of saying we can pass functions as parameters to other functions, or even return functions from other functions. This is actually one of the core concepts of functional programming (or fp if you’re pressed for time) and can lead to some pretty powerful features. We’ll go through a pretty easy example though so you can build on your understanding of this really nifty feature.
Our Example
For this example we’re going to build a contact list. We’ll make a Person class. Each person has a name, contact information, and their preferred method of contact. In other words, some people want to be emailed, others want to be called. To facilitate the creation of these objects, we’re going to use the power of passing functions as parameters. First, let’s actually write a couple of functions callPerson and emailPerson :
let callPerson = function(phoneNumber) console.log("Dialing " + phoneNumber); > let emailPerson = function(emailAddress) console.log("Emailing " + emailAddress); >
These functions will write to the console that they are calling a phone number or sending an email to a specific address. We’re going to use these functions to build our contact list. Let’s write the Person class:
class Person constructor(name, contactInfo, preferredContact) this.name = name; this.contactInfo = contactInfo; this.preferredContact = preferredContact; > makeContact() this.preferredContact(this.contactInfo); > >
Our person class is constructed by passing the person’s name, contact information, and preferred method of contact. The preferred method of contact is actually going to be a function, and you can see in the person class the makeContact function uses the preferred method passed to the constructor to make contact. Let’s create a person and see what happens:
let erik = new Person("Erik", "555-444-3030", callPerson);
See I am passing to the constructor the person’s name, phone number and the name of the phone call function (ie, without the () at the end). Now, what happens if I try to make contact with this person? Take a look:
> erik.makeContact(); Dialing 555-444-3030
Notice how the person class’s makeContact function uses whatever function was passed to its constructor, passing in the name as a parameter. Let’s see what happens if we use the emailing function:
let lina = new Person("Lina", "smoochiebear@sweetheart.com", emailPerson);
> lina.makeContact() Emailng smoochiebear@sweetheart.com
Again, do you see how the different functions we are passing to the constructor of the Person class are defining how the makeContact method is implemented? Oh by the way, you can also pass anonymous functions:
> let sonya = new Person("Sonya", "Mom", ((x) => console.log("Hi " + x))) > sonya.makeContact() Hi Mom
What’s the use?
This goes beyond mere parlor tricks, this feature has some real uses. Let’s say I have an array of all the contacts:
let people = [erik, lina, sonya]
and we need to contact them all at once. We don’t have time to figure out what their preferred method of contact is, we just need to tell our program to contact them now. Well, because we created our class to take in a function as the preferred method of contact, we can do this quite simply:
> people.forEach(person => person.makeContact()) Dialing 555-444-3030 Emailng smoochiebear@sweetheart.com Hi Mom
Since we defined makeContact for the person class to be a method supplied to the constructor, we can simply iterate through this array of Person objects and tell the loop to run the makeContact method. We already supplied the preferred method of contact, so we don’t need to bother with something like:
// This is an example of what we're trying to avoid if (Person.preferred contact === "email") console.log("Emailing " person.emailAddress); else if (Person.preferred contact === "phone call" // and so on and so on
Conclusion
This was a pretty quick article for such a super awesome concept. I strongly encourage you to play around with this feature of JavaScript to see what it can do for you.
Pass JavaScript Function as Parameter
- Pass a General JavaScript Function as a Parameter
- Pass Both Function and Value to a JavaScript Function
In JavaScript, passing a function as a parameter to another function is similar to passing values. The way to pass a function is to remove the parenthesis () of the function when you assign it as a parameter.
In the following sections, a function pass is demonstrated as a parameter.
Pass a General JavaScript Function as a Parameter
For this drive, we will initiate a function func2 with a code body and directly pass it to the function func1 . Later, after assigning func2 to func1 , we will call the func2 aka function_parameter .
function func1(function_parameter) function_parameter(); > function func2() console.log("okay!"); > func1(func2);
The example depicts that func2 is passed to func1 . And when func1 is called, it checks its argument (func2) and previews the code fenced by func2 .
Pass Both Function and Value to a JavaScript Function
JavaScript allows the passing of function and value together in another function, making functions more dynamic. This declaration will require an input of integer , bool , string , or maybe even a function, and the other parameter is the function parameter.
We will see two examples of this category.
Function and value as function parameters:
function pass(value) return ("Hello " + value); > function receive_pass(x, func) console.log(func(x)); > receive_pass("David", pass);
Two functions as function parameters:
function pass1(value) return ("Hello " + value); > function pass2() return (" Howdy!"); > function receive_pass(func1, func2) console.log(func1("world!")+func2()); > receive_pass(pass1, pass2);
As per the code instances, JavaScript takes functions as a parameter like any other regular data type. The core difference is when a function is called in the parenthesis of the argument, functions should be removed; otherwise, this can cause an error while running.
Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.
Related Article — JavaScript Function
Related Article — JavaScript Parameter
Copyright © 2023. All right reserved