Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Erik
Erik

Posted on

     

Passing Functions as Parameters in JavaScript

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.

First class

This is actually one of the core concepts of functional programming (orfp 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 aPerson 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 functionscallPerson andemailPerson:

letcallPerson=function(phoneNumber){console.log("Dialing"+phoneNumber);}letemailPerson=function(emailAddress){console.log("Emailing"+emailAddress);}
Enter fullscreen modeExit fullscreen mode

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:

classPerson{constructor(name,contactInfo,preferredContact){this.name=name;this.contactInfo=contactInfo;this.preferredContact=preferredContact;}makeContact(){this.preferredContact(this.contactInfo);}}
Enter fullscreen modeExit fullscreen mode

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 themakeContact function uses the preferred method passed to the constructor to make contact. Let's create a person and see what happens:

leterik=newPerson("Erik","555-444-3030",callPerson);
Enter fullscreen modeExit fullscreen mode

See I am passing to the constructor the person's name, phone number and thename 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
Enter fullscreen modeExit fullscreen mode

Notice how the person class'smakeContact 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:

letlina=newPerson("Lina","smoochiebear@sweetheart.com",emailPerson);
Enter fullscreen modeExit fullscreen mode

And we run the make contact method on the object named lina:

> lina.makeContact()Emailng smoochiebear@sweetheart.com
Enter fullscreen modeExit fullscreen mode

Again, do you see how the different functions we are passing to the constructor of thePerson class are defining how themakeContact 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
Enter fullscreen modeExit fullscreen mode

That's crazy huh?

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:

letpeople=[erik,lina,sonya]
Enter fullscreen modeExit fullscreen mode

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-3030Emailng smoochiebear@sweetheart.comHi Mom
Enter fullscreen modeExit fullscreen mode

Since we definedmakeContact for the person class to be a method supplied to the constructor, we can simply iterate through this array ofPerson objects and tell the loop to run themakeContact 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.preferredcontact==="email"){
console.log("Emailing"person.emailAddress);
elseif(Person.preferredcontact==="phone call"{
// and so on and so on

Enter fullscreen modeExit fullscreen mode




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.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Sr. Software Engineer at CallRail building microservices to support 3rd party integrations. PhD student at the University of Nebraska studying bioinformatics, machine learning, and algorithms.
  • Location
    Omaha, NE
  • Education
    BS CIS (2018), MS Software Engineering (2020), PhD Computer Science (in progress)
  • Pronouns
    He/Him
  • Work
    Sr. Software Engineer
  • Joined

More fromErik

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp