DEV Community

Cover image for πŸ” Understanding Scope, Scope Chain & Lexical Environment in JavaScript
ronak wanjari
ronak wanjari

Posted on

πŸ” Understanding Scope, Scope Chain & Lexical Environment in JavaScript

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

Enter fullscreen mode Exit fullscreen mode

πŸ”— 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
Enter fullscreen mode Exit fullscreen mode

🧠 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

JavaScript #Scope #Devsync #LexicalEnvironment #WebDev #JSIntern

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.