JavaScript Variable Scope (with Examples)

JavaScript Variable Scope

In this article, we will learn about variable scope in JavaScript. We will explore what it is and different types of variable scopes with examples.

What is a Scope?

Scope refers to the availability of the variables and objects in a part of the code. We cannot access the variables however we want. We need to look at their scope. There are mainly three types of variable scopes in JavaScript.

  • Block scope
  • Function scope
  • Global scope

Let’s understand them one by one.

Block scope:

In programming, a block is a set of instructions written inside curly brackets { }. Anything you write inside the brackets is a block.

JavaScript allows us to declare variables using var, let, and const keywords. The var variables can be accessed inside and outside the block.

Here is an example:

<script>
    {
        var num1 = 100;
        console.log("Inside Block " + num1);
    }
    console.log("Outside Block " + num1);
</script>

Output:

Inside Block 100
Outside Block 100

In the above code, we are creating num1 in a block. We are printing it inside and outside the block without any problem. Let’s change the var to let and see what happens.

<script>
    {
        let num1 = 100;
        console.log("Inside Block " + num1);
    }
    console.log("Outside Block " + num1);
</script>

Output:

Inside Block 100
Uncaught ReferenceError: num1 is not defined

It prints Inside Block 100 followed by an error. This is because the let variables are block scoped (they can only be accessed in the block they are declared). If we try to retrieve them outside the block, we will get a reference error. The same thing applies to const variables. We can only retrieve them inside their block.

<script>
    {
        const num1 = 100;
        console.log("Inside Block " + num1);
    }
    console.log("Outside Block " + num1);
</script>

Output:

Inside Block 100
Uncaught ReferenceError: num1 is not defined

So, the let and const variables are block scoped where are the var variables are not.

Function scope:

In JavaScript, every function creates a new scope. All the variables (var, let, and const) are function scoped which means they can only be accessed inside the function.

<script>
  function fun1() {
    var num1 = 100;
    console.log("Inside function " + num1);
  }
  fun1(); // call the function
  console.log("Outside function " + num1);
</script>

Output:

Inside function 100
Uncaught ReferenceError: num1 is not defined

As you can see, we can access the num1 inside the fun1(), but not outside of it. You get the same output if you replace var with let and const.

Note: You may have heard “local scope”. It means that the variables declared inside a function become local to that function. They have function scope.

Global Scope:

When you declare a variable outside any function, it becomes a global variable. It will have global scope which means we can get its value from anywhere in the program. All the variables (var, let, and const) have global scope.

<script>
  var num1 = 200;
  function fun1() {
    console.log("Inside function " + num1);
  }
  fun1(); // call the function
  console.log("Outside function " + num1);
</script>

Outside:

Inside function 200
Outside function 200

In the above code, we have created num1 outside the function fun1(). As a result, it becomes a global variable. We are able to access it anywhere like inside and outside the function. The same thing applies to let and const variables.

There are two things you need to remember.

1. If you create a variable without var, let, and const keywords, it becomes a global variable.

<script>
  function fun1() {
    num1 = 200;
  }
  fun1();
  console.log(num1); // prints 200
</script>

In fun1(), we created num1 without specifying any keyword. So, it became a global variable. We are able to get its value outside the fun1().

2. We can access var global variables using the window object.

<script>
  var num1 = 300;
  console.log(window.num1); // prints 300
</script>

This doesn’t apply to let and const global variables.

<script>
  let num1 = 300;
  console.log(window.num1); // prints undefined
</script>

Note: Do not declare var variables globally because you may end up overriding default window object variables.

What Happens If We Create Global and Local Variables with the Same Name?

Look at the following code:

<script>
  let message = "I'm Global";
  function fun1() {
    let message = "I'm Local";
    console.log(message); // prints I'm Local
  }
  fun1();
  console.log(message); // prints I'm Global
</script>

Output:

I'm Local
I'm Global

We have declared the message variable inside and outside the fun1(). When we try to print its value inside fun1(), JavaScript first searches for the variable in the current scope (function). It if finds it successfully, it prints the value. That is why we got I’m Local in the output.

We are printing the value outside the function which is the global scope. JavaScript searches for the variable in the global scope and prints its value. This is the reason, we are seeing I’m Global in the output.

How Long do Variables Live in JavaScript?

The lifetime of variables starts when they are declared.
The global variables will be deleted when you close the browser window tab.
The variables inside a function will be deleted when the function is executed.

Related:

Leave a Comment