JavaScript Notes
Master JavaScript scope: global, function, block scope, var vs let vs const, scope chain, scope shadowing, and essential interview Q&A with diagrams.
What is Scope?
Scope is the region of your code where a variable or binding is accessible. Every variable you create lives in a scope, and JavaScript uses scope rules to decide which variables are visible at any given point.
One-liner: Scope is the boundary that controls which parts of your code can see and use a variable.
Types of Scope in JavaScript
| Scope Type | Created by | Declaration | Accessibility |
|---|---|---|---|
| Global | Outside all functions/blocks | Anywhere | Entire program |
| Function | function keyword | Inside function | Within function |
| Block | {} curly braces | let/const inside block | Within block only |
| Module | import/export file | Top-level in module | Within module file |
Global Scope
const site = "WoHoTech"; // Global
let language = "JavaScript"; // Global
function showInfo() {
console.log(site); // ✅ Accessible from global
console.log(language); // ✅ Accessible from global
}
showInfo();
console.log(site);WoHoTech JavaScript WoHoTech
Variables declared outside any function or block are in the global scope — accessible everywhere.
Function Scope
function greetUser() {
const greeting = "Hello"; // Function scope — only inside greetUser
const name = "Priya";
console.log(`${greeting}, ${name}!`);
}
greetUser();
// console.log(greeting); // ❌ ReferenceError — not accessible hereHello, Priya!
Variables declared inside a function are function-scoped — they live and die with that function call.
Block Scope — let and const
if (true) {
let blockVar = "inside block";
const blockConst = "also inside block";
var functionVar = "I leak out"; // var ignores block boundaries
}
// console.log(blockVar); // ❌ ReferenceError
// console.log(blockConst); // ❌ ReferenceError
console.log(functionVar); // ✅ "I leak out" — var is function-scopedI leak out
let and const respect block boundaries. var does not.
Scope Chain Diagram
Scope Chain Walkthrough
const site = "WoHoTech"; // Global
function outer() {
const outerVar = "outer";
function inner() {
const innerVar = "inner";
// Looking up each variable:
console.log(innerVar); // Found in inner — immediate scope
console.log(outerVar); // Found in outer — one level up
console.log(site); // Found in global — two levels up
}
inner();
}
outer();inner outer WoHoTech
var vs let vs const — Scope Comparison
function scopeDemo() {
// var: function-scoped, hoisted to undefined
if (true) {
var x = "var";
}
console.log(x); // ✅ "var" — accessible outside block!
// let: block-scoped
if (true) {
let y = "let";
}
// console.log(y); // ❌ ReferenceError — block boundary
// const: block-scoped + immutable binding
if (true) {
const z = "const";
}
// console.log(z); // ❌ ReferenceError — block boundary
}
scopeDemo();var
The Classic for Loop Scope Bug
3 3 3
0 1 2
var i is in the function scope — shared by all iterations. let i creates a new binding for each iteration's block scope.
Scope Shadowing
A variable in an inner scope can shadow (hide) a variable with the same name in an outer scope:
const color = "blue"; // Outer
function paintWall() {
const color = "red"; // Shadows outer `color`
console.log(color); // "red" — inner wins
}
paintWall();
console.log(color); // "blue" — outer unchangedred blue
// More complex shadowing
let value = "global";
function outer() {
let value = "outer"; // Shadows global
function inner() {
let value = "inner"; // Shadows outer
console.log(value); // "inner"
}
inner();
console.log(value); // "outer"
}
outer();
console.log(value); // "global"inner outer global
IIFE — Immediately Invoked Function Expression (Old Module Pattern)
Before modules, IIFEs were used to create isolated scopes:
1 2 1 1
The IIFE runs immediately, creates a function scope around count, and returns an object with controlled access — the original module pattern.
Module Scope
ES Modules have their own scope — top-level variables are NOT global:
// config.js (module)
const API_KEY = "secret-123"; // Module scope — not in window.API_KEY
export const BASE_URL = "https://api.wohotech.com";Only explicitly exported values are accessible from outside the module.
Common Mistakes
❌ Mistake 1 — Accidental Global Variables
function setup() {
config = { theme: "dark" }; // WRONG — no let/const/var → global!
}
setup();
console.log(config); // Accessible globally — pollution!{ theme: 'dark' }// CORRECT
function setup() {
const config = { theme: "dark" }; // Block scoped
}❌ Mistake 2 — Confusing var Scope in Conditionals
function checkAge(age) {
if (age >= 18) {
var status = "adult"; // var is function-scoped!
}
console.log(status); // Works (undefined if age < 18), confusing!
}
checkAge(16);undefined
// CORRECT
function checkAge(age) {
let status;
if (age >= 18) {
status = "adult";
}
console.log(status); // undefined or "adult"
}❌ Mistake 3 — Unexpected Shadowing
let total = 0;
function addItem(price) {
let total = price; // Accidentally shadows outer total!
console.log(`Item: ${total}`);
}
addItem(50);
console.log(`Total: ${total}`); // 0 — outer total untouched!Item: 50 Total: 0
Sometimes shadowing is intentional — but unintentional shadowing is a common source of bugs.
Interview Questions 🎯
Q1. What is scope in JavaScript?
Scope is the region of code where a variable is defined and accessible. JavaScript has global scope (entire program), function scope (within a function), block scope (let/const within {}), and module scope (within a module file).
Q2. What is the difference between function scope and block scope?
- Function scope (
var): variable lives for the entire function — accessible throughout, even after its block ends - Block scope (
let/const): variable lives only within the{}block where it's declared
Q3. What is the scope chain?
The scope chain is the series of nested scopes JavaScript walks through to find a variable. Starting from the current scope, it moves outward through parent scopes until it finds the variable or reaches the global scope (where a ReferenceError is thrown if not found).
Q4. What is scope shadowing?
Scope shadowing occurs when a variable in an inner scope has the same name as one in an outer scope. The inner variable "shadows" (hides) the outer one within its scope. The outer variable is unchanged.
Q5. Why does var in a for loop cause the classic setTimeout bug?
var is function-scoped, not block-scoped. All iterations of the loop share the same var i variable. By the time setTimeout fires, the loop has completed and i is at its final value. Using let creates a new binding per iteration.
Q6. What is the IIFE pattern and why was it used?
IIFE (Immediately Invoked Function Expression) is a function that runs immediately after declaration. It was used to create isolated scope before ES Modules existed — preventing variable leaks to global scope.
Q7. How does module scope differ from global scope?
Module scope is isolated to the file — top-level variables are not added to the global object. Only explicitly exported values are accessible from outside. This prevents naming conflicts and global pollution that plagued pre-module JavaScript.
Q8. Can let and const be re-declared in the same scope?
No. let and const cannot be re-declared in the same scope — SyntaxError. var can be re-declared (it's just ignored). In different scopes (e.g., nested blocks), the inner let creates a new binding (shadowing), not a re-declaration.
Key Takeaways 🔑
- Scope controls variable visibility and lifetime
- Global scope: visible everywhere in the program
- Function scope:
vardeclarations — live for the entire function - Block scope:
let/const— live only within{}block - Scope chain: JavaScript walks outward through scopes to find variables
- Scope shadowing: inner variable hides same-named outer variable
varignores block boundaries — causes the classic loop setTimeout bug- Modern best practice: always use
let/const, nevervar - Module scope keeps file variables private by default
Summary
Scope defines where a variable is accessible in JavaScript. JavaScript has four scope types: global (entire program), function (var declarations), block (let/const within {}), and module (ES module files). Variable lookup follows the scope chain — JavaScript searches from the current scope outward to global. Inner scopes can shadow outer variables with the same name. The most important practical rule: var is function-scoped (ignores blocks, causes the loop bug), while let and const are block-scoped (the modern standard). Understanding scope is prerequisite knowledge for closures, hoisting, and interview questions about JavaScript's execution model.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Scope - Complete Guide with var, let, const & Scope Chain.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, advanced, scope, javascript scope - complete guide with var, let, const & scope chain
Related JavaScript Master Course Topics