In this article, we are going to talk about an important concept of JavaScript called scope
. You will learn about how scope in JavaScript works, and global variables and how they relate to scope.
Let's dive in!
What is scope in JavaScript?
Scope simply means variable access, that is "What variable do I have access to when my code runs?". By default in JavaScript,
we are in the root scope, alias the window object. Let's visualize what we are talking about here.
Assume we write and run a function in your browser console, call it func
as shown below;
function func() {
console.log('func');
}
...and then call the window object, by just typing window
on the console, you see that your function func has been added to the window object. As shown in the image below:
So, we see now that while working in the browser, the window is the root scope, the parent scope.
Now, what if we define a function func, then define a variable a
inside it and try to console.log(a)
outside the function, what do we get? Well, let's see for ourselves...
Hmnnnn... so we got an error which says a is not defined, let's get a hang of what's happening here. Variable a is defined, but within the function func, right. Variable 'a' therefore is limited to that function's scope(within the curly braces of the function). That is, it cannot be used outside of that scope. The only way to correct the given error is to console.log(a) inside the function's scope.
We see from the illustration above that a is now logged on the console.
Global variables and Scope
Global variables are variables that are declared in the global scope. That is, they are declared in the root scope, which means they are present in the window object like we saw previously.
What does this mean?
This means that they can be accessed from anywhere in the JavaScript program, even if they were not declared in the scope of an entirely new function(a child scope).
Suppose we have a variable a
declared outside of a function func
, the variable a
can be used as a variable, and even modified in a child scope function func
.
Let's visualize what we have just learned.
We see how that the global variable can be accessed and used by child scopes in the above illustration.
Next, let's see how the global variable can be modified by child scopes.
We see how that variable a
has been modified globally, not just in the function, after the function was called, and from that instant, a is equal to 13.
Conclusion
We do have many more scenarios of using parent scopes inside of child scopes, like functions inside of functions, but that is beyond the scope of this article.
Recap
In this article, you read about
Root scope and how that by default we are in the root scope, the window object in JavaScript.
How that declaring variables inside of a function is limited to that function.
Global variables and how you can use them in child scopes.
If you have any questions, feel free to ask in the comments section. Until next time, XOXO.
Top comments (0)