JavaScript has a feature called scope. The concept of the scope in not that easy to understand for many new developers but I will try my best to explain them in simple way. Understanding scope will make your code better and key to writing bulletproof code and being a better developer.
What Is Scope?
In JavaScript scope is the set of variables, functions and objects you have accessed to. Scope refers to the current context of your code. scope can be defined globally and locally.
Global Scope
Before writing code in JavaScript, you are in what we call Global Scope. If we declare a variable, It’s considered as Global Variable.
Variables inside the global scope can be accessed and altered in any other scope.
Local Scope
There is typically one global scope and each function defined has its own local scope. Any function defined with in another function has a local scope of the parent function.
If I create function and defined some variables, those variable will be the local variables of that function. Take an example –
Automatically Global
If we assign a value to a variable that has not been declared then that variable will be considered as Global Variable.
I hope you got a better understanding of JavaScript Scope and things around it. Thanks