javascript

Function Scope


JavaScript has function scope: Each function creates a new scope.
Variables defined inside a function are not accessible (visible) from outside the function.
Variables declared with var, let and const are quite similar when declared inside a function.

 

Using `var`

Variables declared with var are function-scoped. They are accessible throughout the entire function in which they are declared, regardless of block scope.

 

Example:

// Using var
function functionScope() {
    if (true) {
        var localVar = 23;
        .console.log(localVar); // Ouput: 23
    }
    console.log(localVar); // Output: 23
}

functionScope();
console.log(localVar); // Error: localVar is not defined

 

Using ‘let’

Variables declared with let are block-scoped. They are accessible only within the block (enclosed by {}) in which they are defined.

 

Example:

function functionScope() {
    if (true) {
        let localVar = 2;
        console.log(localVar); // Output: 2
    }
    console.log(localVar); // Error: localVar is not defined
}

functionScope();

 

Using ‘const’

Variables declared with const are also block-scoped like let, but they have the additional constraint that their value cannot be reassigned once initialized. However, for objects and arrays, while the binding itself cannot be reassigned, the properties or elements inside can still be modified.

 

Example:

function functionScope() {
    if (true) {
        const localVar = 232;
        console.log(localVar); // Output: 232
        localVar = 'Trying to reassign'; // Error
    }
}