Functions as Values
What You'll Learn
You'll learn that in JavaScript, functions are first-class values — meaning they can be stored in variables, passed to other functions, and returned just like numbers or strings.
Functions Are Data
In many programming languages, functions are separate from "regular" values. JavaScript is different: functions are values, just like 42 or "hello".
Think of it like this: if a number is a thing you can store, then a function is an action you can store. Just as you can put a number in a box (variable), you can put a function in a box too.
What This Means Practically
Because functions are values, you can:
Store them in variables:
const greet = function() {
return "Hello!";
};
// greet now holds a function value
console.log(greet()); // "Hello!"
Put them in arrays:
const actions = [
function() { return "first"; },
function() { return "second"; }
];
console.log(actions[0]()); // "first"
Assign them to object properties:
const calculator = {
add: function(a, b) { return a + b; }
};
console.log(calculator.add(2, 3)); // 5
You can pass them around, copy them to other variables, and treat them like any other piece of data. The function remains executable wherever it lands.
Why This Matters
This "first-class" nature is foundational to JavaScript's flexibility. It enables powerful patterns you'll encounter constantly: callbacks, event handlers, and functional programming techniques all rely on treating functions as portable, reusable values.
Key Takeaway: In JavaScript, functions aren't just code blocks — they're values you can assign, store, and pass around like any other data type.