Scope (Global, Local, Block)
Expert-Level Explanation
Scope in JavaScript refers to the visibility of variables.
Global Scope: Variables declared globally (outside of any function or block). These are accessible from anywhere in the code.
Local (function) scope: variables declared within a function. They are only accessible within that function.
Block Scope: Introduced with ES6 through
let
andconst
. Variables declared inside a block{}
are only accessible within that block.
Creative Explanation
Think of scopes as different areas in a house:
Global Scope: The backyard, accessible from anywhere in the house.
Local Scope: A specific room. Items (variables) in this room are only usable inside this room.
Block Scope: A closet within a room. Items placed here are only available in this specific area.
Practical Explanation with Code
var globalVar = "Accessible anywhere";
function myFunction() {
var localVar = "Accessible within this function";
}
if (true) {
let blockVar = "Accessible within this block";
}
Real-world Example
Global Scope: Public park items, like benches, are accessible to everyone in the town.
Local Scope: Items in your home, accessible only to those living in the home.
Block Scope: Items in your locked drawer, accessible only to you.