Rubypic

Ruby Jane Cabagnot

JavaScript Functions: First-Class Citizens Explained

In the world of JavaScript, functions are treated as first-class citizens. This means they can be passed around like any other value — assigned to variables, passed as arguments to other functions, and even returned from functions. This powerful feature of JavaScript not only makes the language incredibly flexible but also opens up a plethora of programming paradigms, such as functional programming.

Understanding First-Class Functions

To understand what it means for functions to be first-class citizens, let’s break down the concept:

  1. Assigning Functions to Variables: In JavaScript, you can assign functions to variables just like you would with any other data type.
const greet = function(name) {
  console.log(`Hello, ${name}!`);
};
greet('Alice'); // Output: Hello, Alice!

  1. Passing Functions as Arguments: Functions can be passed as arguments to other functions, allowing you to create higher-order functions that operate on other functions.

const greet = function(name) {
  console.log(`Hello, ${name}!`);
};

const greetUser = function(greetFunction) {
  greetFunction('Alice');
};

greetUser(greet); // Output: Hello, Alice!