Scope in Detail with example- Essential JavaScript Concepts

1 minute read

Though the concept of scope is not that easy to understand for beginners, yet we have tried to explain it in easiest way in our video tutorial JavaScript Concepts: Scope Example | 0004-02. Understanding of this JS feature will make your code stand out, reduce errors and help you make powerful design patterns with it. Let us deep dive into this through one practical example.

Suppose we have a requirement to add ten buttons and on click of each button we want to show the number of that button i.e. its iteration number. In our video tutorial we will learn how we can avoid the issue faced by using simple for loop if we understand the concept of Scope. We will see how in JavaScript scope works or why JS scope does not honors the curly braces.

In JavaScript block statements like if and switch conditions or for and while loops, unlike functions, don't create a new scope. Variables defined inside of a block statement will remain in the scope they were already in. ECMAScript 6 introduced the let and const keywords. These keywords can be used in place of the var keyword. JavaScript has lexical scoping with function scope. In other words, even though JavaScript looks like it should have block scope because it uses curly braces { }, a new scope is created only when you create a new function. So within each iteration if I want my own scope, the way to do it is create a function and call. That’s the reason it’s a good practice to have functions to do small-small tasks as in these functions we can define our own scope or boundaries.

Please check out our GitHub repository here, to understand Scope in detail with practical example.