February 8th, 2021
Hello everyone, today I'll try to explain what are JavaScript scopes and closures and how to write the code properly by understanding the scopes truly. So without further ado let's dive right into scopes and see what's up with them.
In JavaScript a scope is the way of you defining how to access a variable in general. It basically draws the lines between a global or a local variable. Mainly there are 2 kinds of scope a local and a global one.
In JavaScript when you define a variable outside on any braces or functions your variable is defined as a global variable that mean it can be reached out globally. No matter if the place you try to use the variable is a function or a nested function with lots of outer functions.
This is an unwanted behaviour because it can often lead some unpredictable and hard to find bugs. Better practice would be limiting the availability of your variables via using scopes. Now let's take a look at how can we use the scopes.
When you define a variable inside of a function your function will be automatically belong to that function's scope from that moment on. Let's check that out on examples.
As we can see above while we can reach out "one, two, three" inside of the "scoped" function we can not do the same outside of it.
Defining a new function inside of another one is a widely used practice in many programming languages. When you define a nested function in JavaScript inner function can reach out the outer ones while the opposite is not possible.
As we can see above when "innerNest" function can reach "outer" variable, "outerNest" function can't reach the "inner" variable.
After "let" and "const" added the JavaScript ability of creating scopes are changed with them. When you define a variable inside of any braces with "const" or "let" keywords it'll automatically belong to that scope, while "var" behave like a global one. Let's take a look.
As we can see above while we can easily reach out the "insideOfIfVar" variable outside of the "if check" we defined, we can't do the same for the others.
Everything that are declared inside of a ".js" file are belongs to that specific file if they are not explicitly exported out. When you try to reach out a variable outside of its module without exporting it the chances are you are going to see something like this one.
Scopes are a fundamental part of JavaScript as they are most other languages, therefore it's too important to learn how to use them properly in order to write decent code.
Alright everyone, that was it for today. I hope you enjoyed it. Until next time, take care :)