Understanding Variable Scopes in JavaScript (original) (raw)

Last Updated : 16 Dec, 2024

In JavaScript, scope defines the accessibility of variables in different parts of your code. It determines where a variable can be accessed or modified.

Types of Scope

  1. **Global Scope: Variables declared outside any function or block are accessible everywhere in the code.
  2. **Function Scope: Variables declared with var inside a function are accessible only within that function. Function can be nested in JavaScript and the inner function can access outer function members and this is called Lexical Scope.
  3. Block Scope: Variables declared with let or const inside a block ({}) are accessible only within that block.
  4. **Modular Scope: Introduced in ES6, ES Modules are the standard way to organize JavaScript code into reusable and maintainable chunks. Each module has its own scope, and anything declared within a module is private by default unless explicitly exported.

**Example of Global Scope

JavaScript `

// Using var var x = 10; console.log(x);

// Using let let y = 20; console.log(y);

// Using const const z = 30; console.log(z);

`

**Note: Here let and **const are behaving similar to var but they do not attach to the window object. They are scoped globally but are not properties of window, making them safer and less prone to conflicts.

JavaScript `

var globalVar = "I am global"; console.log(window.globalVar);

let globalLet = "I am block-scoped"; console.log(window.globalLet);

`

global-scope-of-let

Understanding variable scopes in JavaScript

**Examples of Block Scope

JavaScript `

if (true) { var x = 10; // Function-scoped (not block-scoped) let y = 20; // Block-scoped const z = 30; // Block-scoped }

console.log(x); // Output: 10 (accessible outside the block) console.log(y); // Error: y is not defined (block-scoped) console.log(z); // Error: z is not defined (block-scoped)

`

**Example of Function Scope

JavaScript `

function example() { var x = 10; // Function-scoped let y = 20; // Function-scoped const z = 30; // Function-scoped console.log(x, y, z); // Output: 10 20 30 }

example();

console.log(x); // Error: x is not defined console.log(y); // Error: y is not defined console.log(z); // Error: z is not defined

`

**Example of Modular Scope

Math.Js `

const PI = 3.14; function add(a, b) { return a + b; }

module.exports = { PI, add };

App.Js

const { PI, add } = require('./math');

console.log(PI); // 3.14 console.log(add(2, 3)); // 5

`

**Lexical Scope (Closures)

**Lexical scope means a function can access variables from its **outer scope even after the outer function has finished execution.

JavaScript `

function outer() { let outerVar = "I'm in the outer scope!"; function inner() { console.log(outerVar); // Accessing parent's scope } inner(); } outer();

`

Different cases of scope

We have a global variable defined in the first line in the global scope. Then we have a local variable defined inside the function fun().

javascript `

let globalLet = "This is a global variable"; { let localLet = "This is a local variable"; // This is a global variable console.log(globalLet);

// This is a local variable
console.log(localLet);   

}

`

Output

This is a global variable This is a local variable

Let’s move the console.log statements outside the function and put them just after calling the function.

javascript `

let globalLet = "This is a global variable"

function fun() { let localLet = "This is a local variable"

} fun(); console.log(globalLet); console.log(localLet);

`

**Word of caution: Whenever you are declaring variables, always use the prefix let. If you don’t use the let keyword, then the variables are by default created in the global scope. For instance, in the above example.

let’s just remove the keyword let before the declaration of localLet.

javascript `

let globalLet = "This is a global variable";;

function fun() { localLet = "This is a local variable"; }

fun(); console.log(globalLet); // This is a global variable console.log(localLet); // This is a local variable

`

Output

This is a global variable This is a local variable

One of the most asked questions in interviews is the case where the global as well as local variable has the same name. Let’s see what happens then.

javascript `

let globalLet = "This is a global variable"

function fun() { let globalLet = "This is a local variable" } fun(); console.log(globalLet); // This is a global variable

`

Output

This is a global variable

Let’s move the console.log statement inside the function fun().

javascript `

let globalLet = "This is a global variable";

function fun() { let globalLet = "This is a local variable"; console.log(globalLet); } fun();

`

Output

This is a local variable

What if we want to access the global variable instead of the local one here? Well, the window object comes to our rescue. All the global variables declared using the "var" keyword or without using any keyword are attached to the window object and thus we can access the global variable name as shown in the example below.

javascript `

let globalLet = "This is a global variable";

function fun() { let globalLet = "This is a local variable"; console.log(window.globalLet); // This is a global variable } fun();

`

**Output: