By Ronak Wanjari | Intern at Devsync.in @devsyncin
If youβre learning JavaScript (like me, at Devsync.in π), you've probably heard terms like scope, scope chain, and lexical environment. These are core concepts that govern how variables are accessed in JS. Letβs break them down simply.
π What is Scope in JavaScript?
Scope is the context in which variables are declared and accessed. JavaScript has:
Global Scope: Accessible everywhere.
Function/Local Scope: Variables declared inside a function can't be accessed outside.
Block Scope (ES6): Variables declared using let and const are limited to {} block.
let globalVar = 'π';
function show() {
let localVar = 'π';
console.log(globalVar); // β
Accessible
console.log(localVar); // β
Accessible
}
console.log(localVar); // β Error
π What is Scope Chain?
When you try to access a variable, JavaScript looks in the current scope, and if it doesn't find it, it travels up the chain.
const name = 'Ronak';
function greet() {
const greeting = 'Hello';
function sayHi() {
console.log(greeting + ' ' + name);
// JS first checks sayHi -> greet -> global
}
sayHi();
}
Scope chain = sayHi β greet β global
π§ What is Lexical Environment?
Every time a function is created, it gets a Lexical Environment, which is a structure that holds the variable references. It has two parts:
Environment Record β Stores variables/functions.
Outer Lexical Environment Reference β Points to parent scope.
This is why inner functions can access outer variables β it's defined lexically (by location in code).
π₯ Final Thoughts
Scope controls where your variables live.
Scope chain helps JavaScript find them.
Lexical Environment is how they are stored and linked.
Understanding this trio is key to writing bug-free, clean JavaScript code.
Iβm learning these during my internship at devsync.in β and it's helping me a lot! π»β¨
Mentored and guided by @devsyncin
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.