Storing Functions in Data Structures
What you'll learn: How to organize functions by placing them inside arrays and objects to create flexible, dynamic behavior.
The Core Idea
Since functions are first-class values in JavaScript, you can store them in arrays and objects just like numbers or strings. This opens up powerful organizational patterns—imagine having a toolbox (an object) where each tool (a function) has a name, or a list of actions (an array) you can execute in sequence.
Functions in Arrays
You can create an array of functions and call them by index:
const actions = [
function() { console.log("Step 1"); },
function() { console.log("Step 2"); },
function() { console.log("Step 3"); }
];
actions[0](); // "Step 1"
actions[1](); // "Step 2"
Functions in Objects
Storing functions as object properties creates a "dispatch table"—a menu of operations you can invoke by name:
const calculator = {
add: function(a, b) { return a + b; },
subtract: function(a, b) { return a - b; },
multiply: function(a, b) { return a * b; }
};
const operation = "add";
calculator[operation](5, 3); // 8
This pattern lets you dynamically choose which function to run based on user input or program state, rather than writing giant if-else chains.
Why This Matters
This technique is the foundation for command patterns, plugin systems, and event handlers. Instead of hardcoding behavior, you configure it with data structures.
Key Takeaway: Storing functions in arrays and objects lets you organize behavior as data, enabling dynamic function selection and cleaner, more flexible code architectures.