Problem Statement
Explain function scope in JavaScript. How does it differ from block scope?
Explanation
Function scope means variables declared inside a function can be used only inside that function.
Before ES6, variables declared with var followed function scope. They were visible anywhere inside the function body.
With ES6, let and const introduced block scope, which limits the variable to the nearest pair of curly braces.
Block scope is tighter and safer because it avoids unwanted access outside its block.
Use let or const for predictable, bug-free behavior.
Code Solution
SolutionRead Only
function test() {
if (true) {
var a = 10;
let b = 20;
}
console.log(a); // 10 (function scoped)
// console.log(b); // Error (block scoped)
}
test();