JavaScript  : Scopes

JavaScript : Scopes

Scope defines where a variable declaration, function declaration, or any other declarations etc. will be accessible in a program. In Javascript, there are mainly four kinds of scope.

  • Global Scope

  • Local Scope

  • Block Scope

  • Module Scope

Global Scope

The outermost scope. Let's understand it concerning variables and function declarations.

Variable declarations using the var keyword are called in the global scope when they are declared outside of all functions. We can access them from anywhere in the program.

console.log(name); // undefined 

var name = "Subham";

function showName(){
    console.log(name); // Subham
}

console.log(name); // Subham

Variable declarations using let and const keywords are called in the global scope when they are declared outside of all blocks (not within any pair of curly braces). We can access them anywhere in the program, after their place of declaration.

console.log(name); // Reference Error 

let name = "Subham";

function showName(){
    console.log(name); // Subham
}

console.log(name); // Subham

Functions declarations are called in the global scope when they are declared outside of all other functions. We can access them anywhere in the program.

hello() // Hello, I am a global function

function hello(){
    console.log("Hello, I am a global function");
}

hello() // Hello, I am a global function

Local Scope

Local scope is the second level of scoping. Any var declaration within a function block is said to be in the local scope. We can access it only inside the function.

function showName(){
    console.log(name); // Subham
    var name = "Subham";    
    console.log(name); // Subham
}

console.log(name); // Reference Error outside of function showName

Block Scope

Block scope is a modified form of local scope, where any let or const declarations within any block ( inside a pair of braces ) are said to be in block scope. We can access it only inside that block.

Note: A function declaration also forms a block.

// Example of function block
function showName(){
    console.log(name); // Reference Error
    var name = "Subham";    
    console.log(name); // Subham
}

console.log(name); // Reference Error outside of function showName

A block can be simply created with a pair of braces. See below,

// Example of simple block
{
    console.log(name); // Reference Error
    var name = "Subham";    
    console.log(name); // Subham
}

console.log(name); // Reference Error outside of function showName

For you to explore,

  • Learn about module scope.