Functions and Scope
~380 words ยท 2 min read
Function declarations vs arrow functions
Two main ways to write a function:
// Declaration โ hoisted (usable before definition)
function greet(name) {
return `Hello, ${name}!`;
}
// Arrow function โ not hoisted, shorter syntax
const greet = (name) => `Hello, ${name}!`;
The key difference: this
Arrow functions do not bind their own this. They inherit it from the surrounding scope:
const obj = {
name: "Alice",
regular() { return this.name; }, // "Alice"
arrow: () => this.name, // undefined (or window.name)
};
Use regular functions for object methods. Use arrow functions for callbacks and when you want to preserve this from the outer context.
Scope
- Global scope โ accessible everywhere.
- Function scope โ accessible only inside the function.
- Block scope (
let/const) โ accessible only inside{ }.
{
let x = 1; // block-scoped
var y = 2; // function-scoped (leaks out of block)
}
console.log(x); // ReferenceError
console.log(y); // 2 (var ignores blocks)
Closures
A closure is a function that remembers variables from where it was created:
function makeCounter() {
let count = 0;
return () => ++count;
}
const counter = makeCounter();
counter(); // 1
counter(); // 2
Closures are how JavaScript achieves data privacy โ the inner variable count is inaccessible from outside.