Scopes in JavaScript
What is Scope?
- Scope in JavaScript refers to the accessibility of variables, which means, in simpler terms, the variables in the program can be accessed anywhere inside the particular scope.
The IMPORTANCE of Scoping in JavaScript:
- Scoping reduces the namespace collisions, giving us the ability to use the same variable name in different scope.
- Variables cannot be accessed anywhere in the program, only in certain places they can be accessed.
- Scope avoids unintended modifications to the variables if made in other parts of the program.
There are three different types of scope in JavaScript:
- Block Scope
- Function Scope
- Global Scope
Block Scope
Block scope exists inside a set of curly brackets {}, just like a FOR LOOP and an IF statement. Const and Let keywords allow us to declare variables only inside the block scope.
Here’s a code snippet to explain how it works:
Function Scope
Variables inside a function scope can only be accessed within the function. Function scope doesn’t have access to each other scopes.
Here’s a code snippet to explain how it works:
Global Scope
Variables that aren’t declared inside a function or block scopes are considered globally Scope. They can be accessed anywhere in the program.
Here’s a code snippet to explain how it works:
Every function has its own scope and any variable declared within that function can be accessed only from the function and any nested functions.
Nested SCOPE
Like functions in JavaScript, a scope can be nested inside another scope. Also, when writing a code, the inner scope can access variables declared in the outer scope, but not the other way around.
Here’s a code snippet to explain how it works:
Conclusion
Overall, scope refers to an area where a variable is accessible. Just like functions, scopes in JavaScript can be nested. In JavaScript, scopes are created by code blocks and functions. Const and let variables are scoped by code blocks or functions. var variables are scoped only by functions or modules. Scoping is so fun and easy to understand once you get the basics of where you can use the variables and how you should use them. I hope that I was helpful in providing you with information to learn about scoping, and made it a little easier.