Functions as First-Class Citizens in JavaScript

Nozibul Islam
2 min readJul 5, 2023
Functions as First-Class Citizens in JS

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.

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

  1. 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
  1. 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!"
  1. 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
  1. 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
  1. 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] }

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

--

--

Nozibul Islam

Passionate writer exploring diverse topics. Transforming thoughts into words. Join me on a journey of discovery and inspiration.