Member-only story

Demystifying JavaScript Scope: The Quirks and Riddles of JS Scope

The inner workings of scope in JS explained to unravel its tricky parts

Max N
4 min readFeb 24, 2024

If you have written any amount of JavaScript code, you have likely run into quirky behavior around scope. Issues with unexpected values of this or variables seeming to change mysteriously are all too common. In this article, we will demystify JavaScript scope — and uncover some of its less obvious tricks.

Understanding the ins and outs of scope in JavaScript is key to mastering how the language really works under the hood. Let’s start from the basics and work our way to unraveling scope surprises even in experienced JS developers run into at times.

Scoping Down the Basics

Before we get into the tricky parts, a quick refresher on JS scope basics. In JavaScript, scope refers to the accessibility and lifetime of variables. The two most common types of scope are:

  1. Global Scope
  2. Local Scope

Here is a simple example:

// Globally scoped variable 
let color = 'blue';
function printColor() {
// Locally scoped variable
let color = 'red'

console.log(color) // 'red'
}
printColor();
console.log(color) // 'blue' - global not affected

--

--

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