DEV Community

Cover image for Functions as First-Class Citizens in JavaScript
Nozibul Islam
Nozibul Islam

Posted on

Functions as First-Class Citizens in JavaScript

What is a First-Class Function?

First-Class Citizens’ means that functions can be used in the same way as other data types. It implies that functions can be assigned to variables, passed as arguments to other functions, and returned as values. This is a crucial concept in functional programming as it allows us to write more modular and reusable code.

  • Assigned to variables
  • Passed as arguments to other functions
  • Returned as values from functions

Here are some examples of using functions as first-class citizens in JavaScript:

  • Assigning Functions to Variables: You can assign functions to variables and use the variables as you would with any other variable.

Example:

const add = function(x, y) {
  return x + y;
}
console.log(add(5, 4)); // Output: 9
console.log(typeof(add)); // Output: function
Enter fullscreen mode Exit fullscreen mode
  • Passing Functions as Arguments: You can pass functions as arguments to other functions. This is useful for designing higher-order functions or callback functions.

Example:

function greet(name, callback) {
  const message = "Hello, " + name + "!";
  callback(message);
}

function logMessage(message) {
  console.log(message); // Logs "Hello, Nozibul!"
}

greet("Nozibul", logMessage); // Logs "Hello, Nozibul!"
Enter fullscreen mode Exit fullscreen mode
  • Returning Functions as Values: A function can return another function from within. This is useful for creating functions that can be used in subsequent operations, such as currying functions.

Example:

function add(x) {
  return function(y) {
    return x + y;
  };
}

const addFive = add(5);
console.log(addFive(3)); // Output: 8
Enter fullscreen mode Exit fullscreen mode
  • Storing Functions in Arrays: Functions can be stored in arrays just like any other value.

Example:

function add(a, b) {
  return a + b;
}

var arr = [];
arr.push(add);
console.log(arr); // Output: [ [Function: add] ]
console.log(arr[0](2, 5)); // Output: 7
Enter fullscreen mode Exit fullscreen mode
  • Storing Functions in Objects: Functions can be stored as properties of objects.

Example:

function add(a, b) {
  return a + b;
}

var obj = {
  sum: add
};

console.log(obj.sum(5, 7)); // Output: 12
console.log(obj); // Output: { sum: [Function: add] }
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate how functions in JavaScript can be treated as first-class citizens, allowing for powerful functional programming paradigms.

Top comments (0)