DEV Community

loading...
Cover image for A Simple Guide to Scope in JavaScript

A Simple Guide to Scope in JavaScript

kirstybrews profile image Kirsty Brewster Updated on ・2 min read

In Javascript, scope refers to the methods and variables we create and where they are available in our code.

If we don't declare our variables in the correct way, it can lead to some weird behavior. However, if we're aware of some of these peculiarities, it can make debugging much easier in the future. Knowledge is power!

Let's create an app where users can view info on various movies.

Example of global scope

Here is the first variable declaration in our .js file. This variable lives outside of any functions; therefore, it has global scope. We will be able to call on this variable anywhere else in our code from now on, such as when we fetch our movie data.

Fetching movie data

We can also declare variables within functions.

Function scope

Doing so makes that variable only available within that specific function. If we try to access that variable outside of the function, we'll get an error that that variable has not been declared.

Calling an error that's outside of its function scope

Error message

Because of function scope, I don't have to worry about overwriting any of my function-specific variables anywhere else in my code. I can even declare variables with the same name inside of other functions if I want to.

Another type of scope we have available is block scope. This means that you can declare variables -- within an if/else statement, for example -- and it won't be available outside of that block of code.

Here's something else that's important when it comes to scope: we have to use let and const to declare our variables.

If we write variables without these declarations, they automatically become global scope. That means, if we're not careful, we can accidentally overwrite some of our function-specific variables outside of those functions.

2001: A Space Odyssey

Initializing a variable

Overwriting variable from other function

2001: A Space Odyssey - Overwritten

The world certainly doesn't need more articles on scope in Javascript, but these were some of the insights I gained once I started exploring some of the scope peculiarities I was curious about.

Baby working on computer GIF

If you want a more thorough understanding, I highly recommend checking out this article by Dr. Axel Rauschmayer.

Discussion (0)

pic
Editor guide