Functions are the primary building blocks of any JavaScript program. They let you wrap up a block of code, name it, and reuse it. Understanding scope — where variables are accessible — is equally important.
Function Declarations
A function declaration defines a named function that is hoisted to the top of its scope.
Because declarations are hoisted, you can call them before they appear in your code:
Function Expressions
A function expression assigns a function to a variable. It is not hoisted.
Arrow Functions
Arrow functions provide a shorter syntax and do not have their own this binding.
When to Use Each
| Style | Hoisted | Own this | Best For |
|---|---|---|---|
| Declaration | Yes | Yes | Top-level named functions |
| Expression | No | Yes | Callbacks, conditionals |
| Arrow | No | No | Short callbacks, array methods |
Default Parameters
You can assign default values to function parameters.
Rest Parameters
The rest operator ... collects remaining arguments into an array.
Understanding Scope
Scope determines where variables are accessible. JavaScript has three types of scope.
Global Scope
Variables declared outside any function or block are globally accessible.
Function Scope
Variables declared with var inside a function are only accessible within that function.
Block Scope
Variables declared with let or const inside a block ({}) are only accessible within that block.
This is why let and const are preferred over var — they give you more predictable scoping.
Closures
A closure is a function that remembers the variables from its outer scope even after the outer function has returned.
Closures are used everywhere in JavaScript — event handlers, callbacks, module patterns, and React hooks all rely on them.
Higher-Order Functions
A higher-order function either takes a function as an argument or returns a function.
Immediately Invoked Function Expressions (IIFE)
An IIFE runs immediately after it is defined. It creates a private scope.
IIFEs were essential before ES modules existed. Today they are less common but still useful for one-time initialization.
Practical Exercise
Build a simple task manager using closures:
Key Takeaways
- Function declarations are hoisted; expressions and arrow functions are not.
- Arrow functions do not have their own
this— use them for callbacks and array methods. letandconstare block-scoped, giving you tighter control over variable visibility.- Closures let inner functions access outer variables after the outer function has returned.
- Higher-order functions accept or return other functions, enabling powerful composition patterns.