Categories
Java Script Tutorials

First Class Function and Callbacks

First class function or first class citizen in JavaScript. But what are first class in general, According to wikipedia

first-class citizen (also typeobjectentity, or value) in a given programming language is an entity which supports all the operations generally available to other entities

Source

First class function are treated like variables. Variables are assigned values. They are passed as an arguments. Variables are returned. So let’s how these attributes are shared with function.

As an Assignment

Now we have the general idea. Let’s explain it in purely programmatical manner.

// regular variable assignment
const sum = function (a, b) {
  return a+b
}

const result = sum (5 + 5)
console.log(result)
// 10

Now what we did is we have created a function and named it sum. After that we are creating a variable result that holds that function. That’s in the console.log we are printing what ever this function returns. That’s exactly how variable behaves in JavaScript

Side Note: Before the assignment the function was anonymous. The function is named function after assignment. Anonymous are sometimes hard to debug

First Class Function as Callbacks

We have some nice Array manipulation methods. Namely map, filter, reduce and more. The Map method accepts a function which is executed for each item of the array. Let’s see it in action

const primes = [ 3, 7, 11]
const squared = primes.map( function(item) {
  return item ** 2
})

console.log(squared) // [9, 49, 121]

The square of prime numbers are stored in squared variable. This map method accepts function as an argument. Which is the property of First class function.

We call this behavior something like callback function. A function that runs inside another function.

Note

This is one more aspect of first class function i-e returning a function. In JavaScript it is call Closures. It is an advanced topic. However, there are multiple ways to call the Function. Call and Apply; I wrote about them previously.

References

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.