Global and local scope in Javascript

Global and local scope in Javascript

Understand about global and local scope with the help of easy examples and easy explanation.

JavaScript variables can be declared using var, let, or const. The scope of these variables depends on how they are declared and where they are used. Let's explore the concepts of block scope and global scope with an example.

let a = 200;

if (true) {
    let a = 10;
    const b = 20;
    var c = 30;
    console.log("Inner: ", a); // Outputs: Inner: 10
}

console.log(a); // Outputs: 200
console.log(b); // Error: b is not defined
console.log(c); // Outputs: 30

Explanation

  • Global Scope: Variables declared outside any block (e.g., let a = 200;) are in the global scope. They can be accessed from anywhere in the code.

  • Block Scope: Variables declared with let or const inside a block (e.g., inside an if statement) are only accessible within that block. In this example:

    • let a = 10; and const b = 20; are in block scope. They can't be accessed outside the if block.
  • Function Scope: Variables declared with var are function-scoped or globally-scoped if declared outside any function. In this example:

    • var c = 30; is accessible both inside and outside the if block because var does not respect block scope, it only respects function scope.

Key Takeaways

  • Block Scope with let and const: These variables are limited to the block where they are defined.

  • Global Scope with var: Variables declared with var can be accessed outside the block they are defined in if they are not inside a function.

  • Scoping Rules: Understanding these rules helps avoid errors and unintended behavior in your code.

Practical Usage

Block Scope Example

if (true) {
    let blockScoped = "I am block scoped";
    console.log(blockScoped); // Outputs: I am block scoped
}
console.log(blockScoped); // Error: blockScoped is not defined

Global Scope Example

var globalScoped = "I am global scoped";
if (true) {
    console.log(globalScoped); // Outputs: I am global scoped
}
console.log(globalScoped); // Outputs: I am global scoped

Understanding the difference between block scope and global scope is crucial for writing clean, maintainable, and bug-free JavaScript code.