Scope (Global, Local, Block)

Akash ThoriyaAkash Thoriya
1 min read

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 and const. 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.

0
Subscribe to my newsletter

Read articles from Akash Thoriya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Akash Thoriya
Akash Thoriya

As a senior full-stack developer, I am passionate about creating efficient and scalable web applications that enhance the user experience. My expertise in React, Redux, NodeJS, and Laravel has enabled me to lead cross-functional teams and deliver projects that consistently exceed client expectations.