JavaScript Scope

JavaScript Scope

Scope in JavaScript determines where variables can be accessed in your code.

There are three types of scope:


1️⃣ Global Scope

A variable declared outside any function or block is global and can be accessed anywhere.


 


2️⃣ Function Scope (Local Scope)

Variables declared inside a function are local to that function and cannot be accessed outside.


 


3️⃣ Block Scope (ES6)

Variables declared with let and const inside { } are block-scoped.



 


📌 Scope Chain

Inner scopes can access variables from their outer scopes.


 


📌 Lexical Scope

JavaScript uses lexical (static) scope, meaning the scope is determined by the code structure, not runtime.


📌 Function vs Block Scope Chart

Keyword Global Scope Function Scope Block Scope
var ✔ Yes ✔ Yes ❌ No
let ✔ Yes ✔ Yes ✔ Yes
const ✔ Yes ✔ Yes ✔ Yes

🧠 Best Practices

  • Use let and const instead of var

  • Keep variables in the smallest needed scope

  • Reduce global variables to avoid conflicts


🚀 Summary

Type Accessible From
Global Scope Everywhere
Function Scope Only inside the function
Block Scope Only inside { }

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *