DEV Community

Cover image for Understanding First-Class Functions in JavaScript
Aris Zagakos
Aris Zagakos

Posted on • Edited on

Understanding First-Class Functions in JavaScript

Table of Contents

  1. Introduction
  2. Resources

Introduction

JavaScript is a programming language with First-class Functions.

A programming language is said to have First-class Functions when functions in that language are treated like any other variable. For example, in such a language, a function can be assigned as a value to a variable, can be passed as an argument to other functions and can be returned by another function.

Assign a function to a variable

// Assign an Anonymous Function to a variable
const greeting = () => {
   console.log('Hi Mikaela!');
};

// Invoke the function using the variable
greeting();
Enter fullscreen mode Exit fullscreen mode

Pass a function as an argument

const sayHi = () => {
   return 'Hi ';
};

const greeting = (hiFn, name) => {
  console.log(hiFn() + name);
};

// Pass `sayHi` as an argument to `greeting` function
greeting(sayHi, 'Mikaela!');
Enter fullscreen mode Exit fullscreen mode

Return a function

const greeting = () => {
  return () => {
    console.log("Hi Mikaela!");
  };
};

// invoke the inner function

greeting()();
// or
var hi = greeting();
hi();


Enter fullscreen mode Exit fullscreen mode

Let's try another example

Create a function that is called addTwoNumbers. This function takes one number as parameter and it returns another function that takes again one number as parameter and finally returns the sum of these two numbers.


function addTwoNumbers(num1) {
  return (num2) => {
    return num1 + num2;
  };
};

// Invoke the function
const add = addTwoNumbers(10);

// 15
console.log(add(5));
Enter fullscreen mode Exit fullscreen mode

Conclusion

First-class functions are a very important part of the JavaScript ecosystem, using them you can work on powerful design patterns such as higher-order functions, partial function application, callbacks, and much more.

Resources

Top comments (0)