Understanding Scope and Lexical Environment in JavaScript

Navigating the Depths of JavaScript’s Inner Workings

Max N
3 min readMar 18, 2024
Photo by Emre on Unsplash

Scope and lexical environment are foundational concepts in JavaScript that dictate how variables and functions are accessed and managed within code. While these concepts may seem complex at first, mastering them is essential for writing efficient and bug-free JavaScript code.

In this article, we’ll unravel the mysteries of scope and lexical environment, providing clear explanations and real-world examples to guide you on your journey to JavaScript proficiency.

What is Scope?

Scope in JavaScript refers to the accessibility or visibility of variables and functions within a particular context in code. Every variable and function in JavaScript has a scope, which determines where it can be accessed and manipulated.

Global Scope

Variables and functions defined outside of any function or block have global scope, meaning they can be accessed from anywhere in the code, including within functions and blocks.

Example: Global Scope

let globalVar = 'I am global';

function greet() {
console.log(globalVar); // Outputs: I am global
}

greet();

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.