Scope & Closures in JavaScript

From the JavaScript cheat sheet · Functions · verified Jul 2026

Scope & Closures

Understanding scope and closure behavior

javascript
// Global scope
let global = 'everywhere';

// Function scope
function outer() {
  let outerVar = 'outer';
  
  function inner() {
    let innerVar = 'inner';
    console.log(outerVar); // accessible
  }
}

// Closure
function counter() {
  let count = 0;
  return () => ++count;
}
💡 Functions create new scope, blocks create scope for let/const
⚡ Closures remember variables from outer scope even after function returns
📌 var is function-scoped, let/const are block-scoped
🔥 Closures are commonly used for data privacy and factory functions

More JavaScript tasks

Back to the full JavaScript cheat sheet