DEV Community

Cover image for JavaScript Variable Scope Simplified.
Brandon Damue
Brandon Damue

Posted on

JavaScript Variable Scope Simplified.

Scope refers to the availability of variables in our code. Questions like can we use variable declared in one function in another function?, if a function contains another function, can they access each other’s variables?. These two questions are quite simple but can cause great confusion to those who don't understand what is going on. If you have problems understanding how Scopes work in JS, this article will be of great help so without further ado, let's get to it.

There are two types of scopes in JavaScript: global scope and function scope.

Global Scope

Did you know that when you start writing code in a JS file you are automatically pleasing it in a global? Well if you didn't know now you do. The Global scope is the highest scope available and any variable or function you place in this scope is accessible anywhere in the file. What I'm saying in effect is that the two variables and the function declared in the code block below have a global scope.

let a = 22;
let b = 'foobar';
function sayHello() {
 return console.log('Hello there');
};
Enter fullscreen mode Exit fullscreen mode

Local Scope

Functions have a local or function scope available to them. This scope is nested inside the global scope. Inner scopes have access to their outer scopes. What this means in practice is that while inside the function sayHello, we can access the variables a and b. In a function, we can look outwards and access variables in the parent scope, in this case, the global scope. An analogy I often use when talking about scopes is a one-way glass window, the person inside(local scope) is able to see what is going on on the outside but the person outside(global scope or outer local scope) is unable to see what is happening inside. A code example will make everything clearer.

var a = 15;
var b = 10;
function logVariables() {
    var b = 20;
    console.log(a);
    console.log(b);
}
Enter fullscreen mode Exit fullscreen mode

The value of b is updated because b is accessible to the function logVariables as b is found in the global scope, so in our one-way glass analogy, the local scope of logVariables is the person inside seeing everything happening on the outside.

When we try to access a variable, the JavasScript engine first looks at the current scope level. If the variable isn’t found in that scope, it will jump upwards into the parent scope and look there, and keep going upwards and out until it either finds the variable or reaches the global scope. If the variable is not in the global scope, we get a reference error.

It only goes outwards. This means that a function can only access the global scope and the scope of functions it is inside of.

In our case, when we log a and b inside logVariables, the JS engine first checks the local scope inside logVariable for the variables.

When looking for a , it doesn’t find it in the local scope. It then jumps up one level and looks for it in the outer scope. It finds it there and uses that value.
When looking for b , it finds it in the local scope and uses that value. It has no need to go up.

Changing the outer scope

Take a look at the code below for a minute.

var a = 5;
function foobar() {
    a = 10;
    b = 20;
};
foobar();
console.log(x); // -> 10
console.log(y); // -> 15
Enter fullscreen mode Exit fullscreen mode

I'm sure your are probably wondering why the value of a when we logged to the console is 10. Shouldn’t the first log statement print 5 , because the a inside foobar is a new, local version of a? Shouldn’t the second log statement cause an error? Notice that inside foobar , when we set a equal to 10 and b equal to 20 , we don’t use the keyword var . This is the key.

Functions can access and change variables in their outer scope. When we omit var , the JavaScript engine will not create a new instance of a variable in the
local scope. Instead, it will first attempt to find the variable we are changing. If it’s found in the local scope, it’ll change the variable in the local scope. If it’s not, it’ll go up continuously until it finds it.
In the case of a , it looks locally, doesn’t find it, then looks upwards and finds it in the global scope. It will then change the value in the place it finds it.
In the case of b , it doesn’t find it at all. When we’re assigning a variable while omitting var and the engine can’t find that variable, it’ll automatically set the
variable in the global scope. That’s why we see 20 printing out outside the function without any issues.

Note: Declaring variables in the global scope is bad practice. It leads to confusion and bugs that are very difficult to find. It pollutes the global scope.

And thats that about Scopes in JS. See you next time. Happy Hacking.💻

Top comments (0)