A Closer Look at Functions in JavaScript

A Closer Look at Functions in JavaScript

ยท

3 min read

First-Class and Higher-Order Functions

  • About a fundamental property of the JavaScript language, which is the fact that it has first-class functions. This enables us to write higher-order functions. But what's that all about? Well, let's see.
    • First-Class Functions.

    ๐Ÿ‘‰ JavaScript treats functions as first-class citizens.

    ๐Ÿ‘‰ This means that functions are simply values.

    ๐Ÿ‘‰ Functions are just another โ€œtypeโ€ of object.

  • So JavaScript is a language that has first-class functions, which in technical terms means that functions are so-called "First Citizens". In practice, that means that functions are simply treated as values.
  • Now, why does JavaScript work this way? Well, it is simply because functions are just another type of object in JavaScript. And since objects are values, functions are values too and since functions are values, there is a bunch of interesting things that we can do with them, like storing them in variables or object properties.

    ๐Ÿ‘‰ Store functions in variables or properties:

const add = (a , b) => a + b;
const counter = {
value: 57,
inc : function()  { this.value++ }
}

๐Ÿ‘‰ Pass functions as arguments to OTHER functions:

const greet = () => console.log( "Hey Jayesh" );

btnClose.addEventListener ( "Click" , greet )

๐Ÿ‘‰ Return functions FROM functions

๐Ÿ‘‰ Call methods on functions:

counter.inc.bind( SomeOtherObject );
  • Higher-Order Functions

  • Higher-Order Functions

๐Ÿ‘‰ A function that receives another function as an argument ,that return a new function, or both.

๐Ÿ‘‰ This is only possible because of first-class functions.

  • So a higher order function is either a function that receives another function as an argument, or a function that returns a new function.
  • First, for functions that receive another function, we have the same example as before.

1.Functions that receive another function

const greet = () => console.log( "Hey Jayesh" );

btnClose.addEventListener ( "Click" , greet )
  • where addEventListener is a Higher-Order function and greet is a Callback Function.

2.Function that returns new function

function count () {                       // higher-order function
 let counter   =  0;
return function ()  {                      // Return function
counter ++;
};
}
  • Important to Note:

  • Some people think that first-class functions and higher-order functions are the same things, but actually, they mean different things.

  • So first-class functions are just a feature that a programming language either has or does not have. All it means is that all functions are values. That's it.
  • There are no first-class functions in practice, it's just a concept. There are, however, higher-order functions in practice, which are possible because language supports first-class functions.

ย