DEV Community

Awais Butt
Awais Butt

Posted on

Javascript Variables Scope

The visibility of the variables is referred to as the scope.
Javascript has 3 types of scope

  1. Block scope
  2. Function scope
  3. Global scope

Block Scope

There was no idea of block scope before ES6. The let and const keywords in ES6 introduced a new feature called block scoping. The block's variables can't be accessed from outside of it.
Example
{
let x = 10;
}
// x cannot be used here

Function 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.
function Person() {
var personName = "Volvo"; // Function Scope
}

Global Scope

Global scope variables can be accessed from anywhere in the program. When defined outside of a block, variables declared using var, let, and const are very similar.
let x = 20 // Global scope

Top comments (0)