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.
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.
We can also declare variables within functions.
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.
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.
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.
If you want a more thorough understanding, I highly recommend checking out this article by Dr. Axel Rauschmayer.
Top comments (0)