JavaScript Variable Scope

Scope of Variables

Scope refers to the visibility of variables. In other words, which parts of your program can see or use it.

It determines the accessibility (visibility) of variables. In JavaScript, objects and functions are also variables. Scope determines the accessibility of variables, objects, and functions from different parts of the code.

The lifetime of a JavaScript variable starts when it is declared. Function (local) variables are deleted when the function is completed. In a web browser, global variables are deleted when you close the browser window (or tab).

Function arguments (parameters) work as local variables inside functions.

In JavaScript there is 3 types of scope:

  • Block scope [let and const keywords]
  • Function scope [ var keyword]
  • Global scope

Block Scope

ES6 provides the let and const keywords that allow you to declare variables in block scope.

Generally, whenever you see curly brackets { }, it is a block. It can be the area within the if, else, switch conditions or for, do while, and while loops.

See the following example:

function say(message) {
    if(!message) {
        let greeting = 'Hello'; // block scope
        console.log(greeting);
    }
    // say it again ?
    console.log(greeting); // ReferenceError
}

say();

In this example above, we reference the variable greeting outside the if block that results in an error.

Remember : curly brackets { } এর ভিতরে var keyword ব্যবহার করে কোন variable declare করলে সেটা বাইরে হতে ও access করা যায়।

কেননা let এবং const keyword ব্যবহার করে variable declare করলে scope হবে শুধু মাত্র curly brackets { } ভিতরে ।

যেমন উপরের উদাহরনটি যদি modify করি এভাবে নিচের মত করে তাহলে এবার আর কোন Error দেখাবে না ।

function say(message) {
    if(!message) {
        var greeting = 'Hello'; // block scope
        console.log(greeting);
    }
    // say it again ?
    console.log(greeting); // ReferenceError
}

say();

Local Scope