Functions are also Objects in Javascript

  • A function is an instance of Object Type
  • A function behaves like any other object
  • We can store function in a variable
  • We can pass a function as an argument to another function
  • We can return a function from a function

In Javascript we say that we have First class functions. The top 3 points we have already covered in previous blogs. Let’s discuss point 4 and point 5 in detail.

Passing Function as Argument

Here I will write a function which will receive an array as an argument, and return a new result array and do the calculation based on function passed as an argument.

Here fn function is called as callback functions, which is passed as an argument and they are called later when needed. Here callback function is called at line 309 which inserting elements in the new array arrRes.

Let’s call the arrayCalc function

Let’s write one more callback function to check if the person has the right to vote or not.

Functions Returning Functions

Let’s understand this with help of an example. Create a function which will create interview questions for different jobs.

How to do this ?
For each job we will return a function that builds a String using person name as an input. Basically, a function returning another function.

Here functions inside the if/else if/else are anonymous functions as they do not have any name.

Also, function interviewQuestion will return us an entire function which we can use later. And this is possible because functions are always First Class Functions in Javascript as they are effectively objects. So we can say that we simply return an object that happens to be a function.

Let’s call it now

We will store it i a variable just like the function expression about which we discussed in the previous blogs. teacherQuestion will be a reference to a function returned.
Now calling the teacherQuestion by passing in the name.

We can use the Questionnaire, for as many teachers as we want as a generic function is being return from interviewQuestion. We just require to pass the arguments to teacherQuestion.

We can call the function in some different way as well as shown below

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts