Scope

Where can i access my variable in my code(where is the variable in my code).

Function Scope:

  • Every Execution context has a link with the outer environment or link with its parent environment.

var name = "Vijay";
function sayName() {
    console.log(name); // Vijay
    var nickName = "Deepak";
    console.log(nickName); // Deepak
    return function subName() {
        console.log(name); // Vijay
        console.log(nickName); // Deepak
        var nickName2 = "Vishnu";
        console.log(nickName2); // Vishnu
    }
    console.log(nickName2); // Reference Error: nickName2 id not defined
}

var myNameFn = sayName();
myNameFn();

we can access the parent variables from any of its child, but not from parent to child.

Note: As mentioned in the optimized code topic not to use eval() and with in JavaScript, it may confuse the JavaScript engine regarding the scope while optimizing the code, some times it may de-optimize the code.

Block Scope:

A variable created inside a curly braces "{ }", cannot be accessible outside.

  • Block scope is introduced in JavaScript as ES6.

  • variables should be declared with "let" or "const" key word.

Function VS Block Scope:

// Function Scope
function alpha() {
    var message = "Hello";
}
console.log(message); // Reference Error: message is not defined
if (5>1) {
    var message = "Hello";
}
console.log(message); // Hello

// Block Scope
if (5>1) {
    let message = "Hello";
    const name = "John";
}
console.log(message); // Reference Error: message is not defined
console.log(name); // Reference Error: name is not defined

Last updated