Functions are First-Class Citizens in JavaScript
📍 What Does "First-Class Citizens" Mean?
In JavaScript, functions are first-class citizens. This means that functions are treated just like any other value — they can be:
- 📦 Assigned to variables
- 🔁 Passed as arguments to other functions
- 🔨 Returned from other functions
- 📚 Stored in objects and arrays
Note
💡 First-class functions are a key enabler of functional programming patterns like callbacks, higher-order functions, and closures in JavaScript.
1️⃣ Assigning Functions to Variables
Function as Variable
const greet = function(name) {
return "Hello, " + name;
};
console.log(greet("Alice")); // Hello, AliceYou can store a function in a variable just like you would store a number or string.
2️⃣ Passing Functions as Arguments
Function as Argument
function sayHello() {
console.log("Hello!");
}
function executeCallback(callback) {
callback(); // invoke the function passed
}
executeCallback(sayHello);You can pass functions into other functions as arguments. This is called a callback. 🔁
3️⃣ Returning Functions
Function Returning Another Function
function multiplier(factor) {
return function(num) {
return num * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // 10This is an example of a higher-order function — a function that returns another function.
4️⃣ Functions in Arrays or Objects
Stored in an object:
Function in Object
const mathOps = {
add: function(x, y) {
return x + y;
}
};
console.log(mathOps.add(2, 3)); // 5Stored in an array:
Function in Array
const funcs = [
() => console.log("One"),
() => console.log("Two")
];
funcs[1](); // Two⚙️ Real-World Use Case: setTimeout
Function as Callback
setTimeout(function() {
console.log("3 seconds later...");
}, 3000);Here, an anonymous function is passed as a callback to setTimeout. It executes after 3 seconds. 🕒
🧠 Why This Matters
Because functions are first-class citizens:
- You can write expressive, modular code
- Functional programming is possible
- Techniques like currying, partial application, and decorators become viable
✅ Summary
- Functions are values — just like strings, numbers, or objects
- You can assign, pass, return, and store them
- This feature makes JavaScript flexible and expressive 🎯
📚 Resources
>>“In JavaScript, functions aren’t just tools — they’re citizens with full rights.” 👑