Assigning Functions to Variables
What you'll learn: How to store functions in variables so you can pass them around, rename them, or invoke them whenever needed.
The Core Idea
In JavaScript, functions are first-class citizens, meaning they're values just like numbers or strings. You can assign a function to a variable exactly like you'd assign let x = 5. Once stored, the variable becomes a reference to that function, and you can call it using the variable name.
How It Works
You can assign both function expressions and declarations:
// Function expression assigned to a variable
const greet = function() {
return "Hello!";
};
// Call it using the variable name
console.log(greet()); // "Hello!"
// You can reassign to a different variable
const sayHi = greet;
console.log(sayHi()); // "Hello!"
Even declared functions can be assigned:
function add(a, b) {
return a + b;
}
// Store the function in a new variable
const sum = add;
console.log(sum(3, 4)); // 7
Why This Matters
Storing functions in variables lets you:
- Rename functions for clarity in different contexts
- Pass functions to other parts of your code
- Organize multiple related functions in data structures (coming soon!)
Think of it like labeling a tool: the hammer doesn't change, but you can call it "hammer," "mallet," or "tool" depending on where you store the reference.
Key Takeaway: Functions are values in JavaScript—assign them to variables to reference and invoke them by any name you choose, enabling flexible and dynamic code.