Member-only story
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:
- Global Scope
- 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