Different Types of Scope in JavaScript
Tags: webdev, javascript, beginners, tutorial
Published: 2023-09-04 12:25:30

Scope is a term that refers to the visibility and accessibility of variables, functions, and objects in a program. In other words, scope determines where and how we can use these elements in our code.

JavaScript has three types of scope: global scope, function scope, and block scope. function and block scope are also known as Local Scope. Let’s look at each one in detail.

## Global Scope

Global scope is the outermost or top-level scope in a JavaScript program. Any variable, function, or object that is declared outside of any function or block belongs to the global scope. These elements are accessible from anywhere in the program, even inside other functions or blocks.

```js
var firstName = "Jeet"; // global variable
function greet() {
  console.log("Hello, " + firstName); // access global variable inside function
}
greet(); // Hello, Jeet
console.log(firstName); // Jeet

```

In the above code, the variable firstName is declared in the global scope and can be used both inside and outside the greet function.

However, using too many global variables can be a bad practice, as it can lead to name collisions, pollution of the global namespace, and security risks. Therefore, it is advisable to limit the use of global variables and use local variables whenever possible.

## Function Scope

Function scope is the scope that is created when we define a function. Any variable, function, or object that is declared inside a function belongs to the function scope. These elements are only accessible within the function and cannot be accessed outside of it.

```js
function greet() {
  var name = "Jeet"; // local variable
  firstName.log("Hello, " + firstName); // access local variable inside function
}
greet(); // Hello, Jeet
console.log(firstName); // ReferenceError: firstName is not defined
```

In the above code, the variable `firstName` is declared in the function scope of `greet` and can only be used inside that function. If we try to access it outside of the function, we get a `ReferenceError`.

Function scope also creates a new scope for each invocation or call of the function. This means that each time we call a function, it creates a separate copy of its local variables and parameters. These copies are independent of each other and do not affect each other’s values.

```js
function add(x) {
  var y = 10; // local variable
  return x + y;
}
console.log(add(5)); // 15
console.log(add(7)); // 17
console.log(y); // ReferenceError: y is not defined
```

## Block Scope

Block scope is the scope that is created when we use curly braces `{}` to create a block of code. A block can be a standalone statement or part of a control structure such as an `if` statement, a `for `loop, or a `switch `case. Any variable, function, or object that is declared inside a block belongs to the block scope. These elements are only accessible within the block and cannot be accessed outside of it

However, block scope only applies to variables declared with the keywords `let `and `const`, which were introduced in ES6 (ECMAScript 2015). Variables declared with the keyword `var `are still subject to function scope and **do not** respect block boundaries.


```js
if (true) {
  var x = 10; // var variable
  let y = 20; // let variable
  const z = 30; // const variable
}
console.log(x); // 10
console.log(y); // ReferenceError: y is not defined
console.log(z); // ReferenceError: z is not defined

```

Block scope allows us to create more modular and encapsulated code, as it prevents variables from leaking into the global or outer scopes. It also helps us to avoid name collisions and redeclaration errors, as we can use the same variable name in different blocks without affecting each other.

```js
for (let i = 0; i < 3; i++) {
  console.log(i); // 0, 1, 2
}
console.log(i); // ReferenceError: i is not defined

for (var j = 0; j < 3; j++) {
  console.log(j); // 0, 1, 2
}
console.log(j); // 3
```

In the above code, the variable i is declared with let and follows block scope rules. Therefore, it can only be accessed inside the for loop and not outside of it. The variable j is declared with var and follows function scope rules. Therefore, it can be accessed both inside and outside the for loop. However, this can lead to unexpected results, as the value of j is changed by the loop and does not reflect the intended scope.

## Super Imp Interview Question
**Predict the output of the following code**

```js
for (var i = 1; i <= 4; i++) {
    setTimeout(function() {
      console.log(i);
    }, 0);
  }
```

Try to run this code on an online JS compiler [here](https://onecompiler.com/javascript/) 

## Conclusion
In this article, we learned about the different types of scope in JavaScript: global scope, function scope, and block scope. We also learned how to use the keywords var, let, and const to declare variables in different scopes and how they affect the visibility and accessibility of these variables. We saw that using block scope can help us write more modular and encapsulated code, while avoiding name collisions and redeclaration errors. We hope this article helped you understand the concept of scope in JavaScript better and how to use it effectively in your programs.