So, In one sentence we can define scope as “the area in code from where a variable can be accessed.” or Scope refers to the availability of variables and functions in certain parts of the code.
- Block scope
- Function scope
- Global scope
ES6 introduced let and const variables, unlike var variables, they can be scoped to the nearest pair of curly braces. That means, they can’t be accessed from outside that pair of curly braces.
You can see that
var variables can be used outside the block, that is,
var variables are not block scoped.
Variables declared inside a function is inside the local scope. They can only be accessed from within that function, that means they can’t be accessed from the outside code.
Any variable that’s not inside any function or block (a pair of curly braces), is inside the global scope. The variables in global scope can be accessed from anywhere in the program.
message is defined in the
global scope. We can access it anywhere in the document.
Global variables are available for the lifetime of the application.
There are some other scope as well, which is build on basically Global Scope, Function Scope, and Block Scope.
As In the above example, You can see 3 scopes nested within each other. First, the block scope (created due to the
let variable) is nested inside the local or function scope which is in turn nested inside the global scope.
Lexical Scope (also known as Static Scope) literally means that scope is determined at the lexing time (generally referred to as compiling) rather than at runtime.
myString() function is accessing the global variable
str which is defined before method function
Why does scope exist?
Scopes can create execution context for JS engine. For example, when the engine starts executing a function, all the variables defined inside the function are allocated to memory. Once the function is done executing, the variables are destroyed. This will keep the memory clean and provides a proper execution context to the JS engine.
This will also help developers easily deal with bugs since codes can be looked at in isolated pieces. It will also take care of variable naming issues since we can repeat the same variable names in different scopes.
Variables declared in global scope should be minimum, as global scope variables are in the memory until application closes. Make sure any variable is only within the necessary scope. Principle of least accessibility should be practiced.
That’s all for this article and with that, it’s a wrap! I hope you found the article useful. Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!