Variable Scopes in JavaScript

Variable Scopes in JavaScript

Understand global, local and block-level scopes in Javascript

1. Introduction

In this tutorial, we're going to learn about scopes in Javascript. Let's start with some basics of what scope is and the different types of scope.

Definition

Scope means the visibility of a variable inside our code. Outside of scope, we cannot access the variable.

Types of Scope

  1. Global Scope
  2. Local Scope
  3. Block Scope

Let's start with Global Scope.

2. Global Scope:

When a variable is not defined inside any function or block then that is available globally and can be accessed from anywhere.

In this case, the Javascript engine adds this variable to the global execution context, so that this variable becomes available to every piece of code.

Anything that has global scope goes inside the global execution context.

Global Scope Example

Let's write a small program to demonstrate this:

var globalVariable = 'Hello';
function foo() {
  if (true) {
    console.log("Inside block: " + globalVariable);
  }
  console.log("Inside function: " + globalVariable);
}
foo();
console.log("Outside function: " + globalVariable);

/* Console
=======================
Inside block: Hello
Inside function: Hello
Outside function: Hello
======================= 
*/

As shown above, the variable globalVariable is defined outside the function. And it is available in all three levels - block, local and global scopes.

All the three console statements will be printed successfully as shown in the console output.

Special Case for Global Scope

If you directly assign a value to some variable without declaring it then that variable will have global scope.

That's why we should be extra careful with this otherwise it may lead to unwanted bugs.

Let's assign a value to a variable inside a function and see what happens:

function foo(){
    fooVar = "Global Test";
    console.log("Inside Function: "+fooVar);
  }
  foo();
  console.log("Outside Function: "+fooVar);

  /*
  Console
  =============================
  Inside Function: Global Test
  Outside Function: Global Test
  =============================
  */

As shown above, fooVar variable will be created automatically in the global context and will be available inside and outside of the function.

Console output shows that both the console log statements are printed successfully.

3. Local Scope:

When a variable is defined inside a function then it is locally present inside that function only.

It is also called Function Scope, internally the Javascript engine creates function execution context and put this variable inside it.

That's how this variable is available inside the function.

Local Scope Example

Let's write another program to demonstrate this.

We've defined a variable - functionVariable inside a function foo:

function foo() {
  var functionVariable = 'Hello';
  if (true) {
    console.log("Inside block: "+functionVariable);
  }
  console.log("Inside function: "+functionVariable);
}
foo();
console.log("Outside function: "+functionVariable);

/* Console
======================================================
Inside block: Hello
Inside function: Hello
Uncaught ReferenceError functionVariable is not defined
======================================================
*/

Here, as we can see in the console output, the functionVariable will be available throughout the function but not available outside the function in the global scope.

4. Block Scope:

When we define a variable within a block, the scope of that variable remains inside it and cannot be accessed from outside.

Block scope can be defined using the let and const keywords.

Note: Using the var keyword it's not possible to define block-level scope. If you try to define the block-level scope with var then that variable will be available throughout the enclosing function.

I've explained the difference between let, var and const in one of my previous Twitter threads where I've explained how these three keywords are different from a scope point of view.

Block Scope Example

Let's write a function foo and define if block inside it and define a variable blockVariable inside it:

function foo() {
  if (true) {
    let blockVariable = 'Hello';
    console.log("Inside block: " + blockVariable);
  }
  console.log("Inside function: " + blockVariable);
}
foo();
console.log("Outside function: " + blockVariable);

/* Console
======================================================
Inside block: Hello
Uncaught ReferenceError blockVariable is not defined
Uncaught ReferenceError blockVariable is not defined
======================================================
*/

When we'll run the program we will find that the console statement inside the block gets executed.

But the console statement inside function and outside function will not be executed.

5. Conclusion

We've seen different types of scopes in Javascript along with an example. The examples mentioned in this article can be found on the GitHub Repository

If you find the repository helpful don't forget to rate the repository and fork it for more future updates.

❤️ Thanks for Reading

Did you like this article? Leave feedback in the comments below. Every Monday, I write an article on Java, Javascript and Fullstack Development.

Stay tuned for more future articles.

If you like this article you might like my previous articles on Java as well:

What is serialVersionUID in Java?

Top 10 Eclipse Tips and Tricks for Java Developers in 2022

Happy Reading :)