Loading...
Loading...
Functions as values. Store them, pass them, return them.
Two ways to create functions — different behavior.
// Function Declaration: function greet(name) { return "Hello, " + name; } // ✓ Hoisted — can call before definition // ✓ Has a name in stack traces // ✓ Stands alone as a statement
✓ Hoisted to top of scope
// Declaration: works before definition sayHi(); // "Hi!" ← hoisted function sayHi() { return "Hi!"; } // Expression: error before definition sayBye(); // TypeError! const sayBye = function() { return "Bye!"; };
Functions without a name — used as values.
// Anonymous — no name after 'function': const greet = function(name) { return "Hello, " + name; }; // Named expression — has a name: const greet = function greetFn(name) { return "Hello, " + name; }; // greetFn is only visible inside itself (for recursion) // Outside, only 'greet' works
Common uses of anonymous functions:
// 1. Array callbacks: [1, 2, 3].map(function(n) { return n * 2; }); // 2. Event handlers: button.addEventListener("click", function() { console.log("clicked"); }); // 3. Immediately executed: (function() { console.log("runs now!"); })();
In JavaScript, functions are values — just like numbers or strings.
Store in variable
const fn = function() {}
Store in array
const fns = [fn1, fn2]
Pass as argument
arr.map(fn)
Return from function
return function() {}
// Functions as object values: const math = { add: function(a, b) { return a + b; }, sub: function(a, b) { return a - b; }, }; math.add(2, 3); // 5 // Functions in an array: const transforms = [ function(x) { return x * 2; }, function(x) { return x + 10; }, function(x) { return x ** 2; }, ]; transforms[0](5); // 10
Immediately Invoked Function Expression — runs as soon as defined.
// IIFE pattern: (function() { const secret = "hidden"; console.log("I run immediately!"); })(); // 'secret' is not accessible here // console.log(secret); // ReferenceError
// With parameters: (function(name) { console.log("Hello, " + name); })("World"); // "Hello, World"
You can pass arguments to an IIFE just like any function call.
Common questions about function expressions.