Understanding Lexical Scope and Closures in JavaScript: A Practical Guide

Mastering these concepts will level up your JavaScript skills

Max N
3 min readMar 20, 2024
Photo by Albert S on Unsplash

In the world of JavaScript, understanding lexical scope and closures is crucial for writing efficient and maintainable code. These concepts may seem daunting at first, but once you grasp them, they become powerful tools in your arsenal. In this article, we’ll dive into lexical scope and closures, exploring them through practical examples and code snippets.

Lexical Scope: Where Variables Live

Lexical scope, also known as static scope, refers to the accessibility of variables based on their physical location within the source code. In simpler terms, it determines where a variable is available for use. JavaScript uses lexical scoping, which means the scope of a variable is determined at compile time, not at runtime.

Let’s start with a basic example:

function outerFunction() {
const outerVar = 'I am outside the innerFunction';

function innerFunction() {
console.log(outerVar); // Output: 'I am outside the innerFunction'
}

innerFunction();
}

outerFunction();

In this example, the variable outerVar is declared within the outerFunction. However, it's accessible…

--

--

Max N
Max N

Written by Max N

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

No responses yet