Problem Statement
Explain the different types of scope in JavaScript: global, function, and block scope.
Explanation
Scope determines where variables are accessible in your code.
Global scope:
Variables declared outside any function or block. Accessible everywhere in your code. In browsers, global variables become properties of window object. Be careful with globals because they can be modified from anywhere.
Function scope:
Variables declared inside a function. Only accessible within that function. This includes var, let, and const. Function scope creates privacy and prevents variables from leaking out.
Block scope:
Variables declared with let or const inside curly braces. Only accessible within that block. Blocks include if statements, for loops, while loops, or any curly braces. Block scope was introduced in ES6. Variables declared with var ignore block scope and use function scope instead.
Scope chain:
JavaScript uses a scope chain to look up variables. It starts in current scope. If not found, moves to parent scope. Continues until reaching global scope. If still not found, you get ReferenceError. Inner functions can access outer variables, but outer functions cannot access inner variables.
Lexical scoping:
JavaScript uses lexical scoping, also called static scoping. Scope is determined by where code is written, not where it is called. Inner functions remember their outer scope even after outer function finishes. This is the basis for closures.
Best practices:
Minimize global variables. Declare variables in smallest scope needed. Use let and const for block scope. Never rely on variable leaking from blocks.
Code Solution
SolutionRead Only
// GLOBAL SCOPE
let globalVar = 'I am global';
var alsoGlobal = 'Me too';
function test() {
console.log(globalVar); // Accessible everywhere
}
console.log(globalVar); // Works
// Global variables on window (browser)
var x = 10;
console.log(window.x); // 10
let y = 20;
console.log(window.y); // undefined
// FUNCTION SCOPE
function calculate() {
let result = 10 * 5;
var temp = 100;
console.log(result); // 50
console.log(temp); // 100
}
// console.log(result); // Error!
// console.log(temp); // Error!
// BLOCK SCOPE
if (true) {
let blockVar = 'I am block scoped';
const alsoBlock = 'Me too';
var notBlock = 'I leak out!';
console.log(blockVar); // Works
}
// console.log(blockVar); // Error!
console.log(notBlock); // Works! (BAD)
// Block scope in loops
for (let i = 0; i < 3; i++) {
console.log(i);
}
// console.log(i); // Error!
for (var j = 0; j < 3; j++) {
// j leaks out
}
console.log(j); // 3 (leaked)
// SCOPE CHAIN
let outer = 'outer';
function first() {
let middle = 'middle';
function second() {
let inner = 'inner';
console.log(inner); // Accessible
console.log(middle); // Accessible
console.log(outer); // Accessible
}
second();
// console.log(inner); // Error!
}
first();