javascript

Variable Scope


 

Scope of a variable means accessible of a particular variable within the program.

There are three variable scopes in JavaScript which are as follows:

  • Local Scope
  • Function Scope
  • Global Scope

 

1. Local Scope:

Variables declared inside a function have local scope and can only be accessed within  that function

 

Example:

    function localScope(){
        var localVariable = "Local Value";
        console.log(localVariable); // Accessing local variable
    }
    console.log(localVariable); // variable not accessible

    localScope(); // Outputs: "Local Value"

 

2. Function Scope

Variables declared using var have function scope, meaning they are only accessible  within the function where they are defined.

 

Example:

    function functionScope(){
        if (true) {
            var functionVariable = "Value";
            console.log(functionVariable); // Accessing function-scoped variable
        }
        console.log(functionVariable); // Accessible here as well
    }
    console.log(functionVariable); // Variable not accessible

    functionScope();

 

3. Global Variable

Global scope refers to the outermost scope where variables are declared outside of  any function or block.


Example:

var globalVariable = "Global scope";

function globalFunction() {
    console.log(globalVariable); // Accessing global variable within a function
}

globalFunction(); // Outputs: "Global scope"

console.log(globalVariable); // Outputs: "Global scope"

 

It's important to understand scope in JavaScript, as it can impact variable accessibility and prevent unintended variable conflicts. Additionally, the introduction of let and const in ES6 has provided developers with better control over block-level scoping.