To understand what is Scope and how Hoisting works.
To differentiate types of Scope.
Scope
The understanding of scope is a key part to your growth as a JS developer. Read this section slowly, and refer back to it often, as some of the most common misunderstandings of JS stem from scope problems. At a base level, JavaScript has function scoping. This means that when we declare variables inside of a function, they are only accessible to that function. Function calls create new scope. Consider the below diagram:
In this example, we have two levels of our scope. Global scope refers to everything in our global namespace. In this example, Global contains no variables. The addNumbers scope refers to all the variables that exist within that function call.
Note:Global scope is never actually empty, however. Anytime we declare a variable globally, it needs to share namespace with all of the objects JavaScript already makes available to us, like console, document, and Math.
Scope and Hoisting
Scope
The understanding of scope is a key part to your growth as a JS developer. Read this section slowly, and refer back to it often, as some of the most common misunderstandings of JS stem from scope problems. At a base level, JavaScript has function scoping. This means that when we declare variables inside of a function, they are only accessible to that function. Function calls create new scope. Consider the below diagram:
In this example, we have two levels of our scope. Global scope refers to everything in our global namespace. In this example, Global contains no variables. The addNumbers scope refers to all the variables that exist within that function call.
Note: Global scope is never actually empty, however. Anytime we declare a variable globally, it needs to share namespace with all of the objects JavaScript already makes available to us, like
console
,document
, andMath
.Now let's see something more complex:
Finally, consider what would happen when...