Skip to main content

Scope and Closures

Understanding Scope is the key to mastering JavaScript. It dictates the accessibility and visibility of variables across different parts of your code.

1. Global vs Local Scope

  • Global Scope: Variables defined outside of any function or block. They are accessible entirely everywhere.
  • Local (Function) Scope: Variables defined inside a function() are locked inside. Outside code cannot reach them.
  • Block Scope: Only applies to let and const. Variables defined inside { curly braces } (like an if statement) cannot be seen outside that block.
let globalVar = "I am everywhere!";

function testScope() {
let functionVar = "I am locked in here!";
console.log(globalVar); // Accessible!
}
testScope();

// console.log(functionVar); // ReferenceError: functionVar is not defined

2. Scope Chain

Whenever JS tries to access a variable, it looks in the current local scope first. If it doesn't find it, it moves "up" the chain to the parent scope, continuing all the way to the Global Scope until it finds the variable.

3. Closures

A heavily tested interview topic! A Closure is when a function remembers the variables from its outer scope, even after that outer function has fully returned and finished executing.

function makeCounter() {
let count = 0; // Private outer variable

// Returning an inner function (the Closure!)
return function() {
count++;
return count;
}
}

const myCounter = makeCounter();
// makeCounter() has finished executing... but the inner function Remembers 'count'.

console.log(myCounter()); // 1
console.log(myCounter()); // 2
console.log(myCounter()); // 3