JavaScript scope

What is Scope in JavaScript?

Within JavaScript, scope denotes the specific environment within our code where variables are defined and can be utilized. Essentially, it determines the reach of a variable or function within JavaScript and where it can be accessed at a later point in time.

A scope refers to the area within code where expressions and values can be accessed. This means that when a variable is declared within a function, it is only accessible within that specific function.

Types of Scopes in JavaScript

JavaScript encompasses various scope types, including global scope, local scope, function scope, block scope, and lexical scope. Let's delve deeper into each of these scope categories:

Global Scope

In JavaScript, the global scope refers to the accessibility of a variable or function throughout the entire program. It is the default and widely used scope for variables and functions.

How can we declare variables in Global Scope?

Within the overarching scope, a variable is accessible from any section of the JavaScript code.

Example

Example

var pet = 'cat';

function printPet() {

    console.log(pet);

}

In the provided illustration, a variable named "pet" was initialized with the value "cat". Additionally, a function named "printPet" was created to output the value of the pet variable to the console.

The pet has been declared in the global scope, making it accessible within the "printPet" function.

Local Scope

In JavaScript, local scope refers to the accessibility of a variable or function within the confines of the current code block. When a variable is defined locally, it is restricted to the specific block of code, function, or conditional statement where it is declared.

How can we declare variables in the local Scope?

In order to establish a local scope, it is necessary to employ curly braces:

Example

An illustration can help clarify the concept of defining local scope in JavaScript:

Example

{ var car= 'BMW'; }

console.log(car);

The diagram shown above illustrates the declaration of a variable called car initialized with the string value 'BMW'. To establish a confined scope for the variable, we employed curly brackets.

The variable 'car' is currently within the local scope, making it inaccessible outside the curly braces. Accessing the variable inside the curly braces will ensure its availability within that scope.

Function Scope

The concept is akin to the local scope where variables and functions are defined within a function and are only accessible within that specific function. Variables declared inside a function are not reachable from outside the function, and they can be declared using keywords like var, let, and const, which behave similarly when used within a function.

Example

Example

Function printCar () {

var car = 'Audi';

console.log (car);

}

In the example provided, a function named "displayVehicle" has been created. It is necessary to declare a variable named 'vehicle' and assign it the value 'Tesla'.

It is necessary to declare the variable 'car' within the "printCar" function to limit its scope to only within that function. Attempting to access the variable outside of the function will result in an error.

Block Scope

Utilizing block scope enables the creation of variables and functions that are restricted to a specific code block. This scope is commonly applied within conditional statements and loops to manage variable scope effectively.

Put simply, block scope can be visualized as a collection of nested compartments inside a bigger container, where each compartment has its own unique variables.

How can we declare a variable in Block Scope?

If a variable is defined within a block scope, it can only be accessed within that specific block where it is declared. Such variables can be likened to concealed gems inside a nested doll, recognizable and usable solely within their individual compartments.

For Example:

Example

if (true){

    let blockVariable = "i am in block scope";

    console.log(blockVariable);

}

Within this code snippet, we have established the blockVariable within the scope of the block that is formed by the if statement, making it unavailable for access outside of this block.

Lexical Scope

JavaScript introduces a more intricate form of scope known as lexical scope, which differs from other scopes and is alternatively referred to as static scope or compile-time scope.

This implies that the accessibility of a variable is defined by its placement in the code. Put simply, variables can be accessed within the scope of their containing variables.

Example:

Example

var vehicle = 'Jaguar';

function printVehicle() {

    console.log(vehicle);

}

In this instance, a variable titled "car" has been declared with the assigned value of "Jaguar". Additionally, a function named displayCar has been established.

Since the variable "vehicle" was declared in the global scope, it can be accessed within the "printVehicle" function as well. However, attempting to access "vehicle" within a code block will result in it not being accessible.

Example

Example

if (true){

    var vehicle = 'Jaguar';

    console.log(vehicle);                                                 

}

console.log(vehicle);

In the example provided, we have the option to declare a variable named 'car' assigned the value of Jaguar. Additionally, we can create a function named 'displayCar'.

The variable named vehicle can be declared in the global scope, making it accessible within the function "printVehicle".

Why is Scope Important in JavaScript?

Several factors emphasize the significance of scope in JavaScript. Here are a few of these factors:

Prevents Variable name conflicts

If two variables are declared with identical names within the same scope in JavaScript, an error will occur, leading to malfunctioning code.

Improve code security

By utilizing scope in JavaScript, we can constrain the accessibility of variables and functions to specific scope limits. This feature serves to safeguard against inadvertent alterations or unauthorized access to confidential information.

Improve code efficiency

Utilizing scope effectively in JavaScript can lead to enhanced code efficiency. By employing the correct scope, we can minimize unnecessary memory consumption and optimize execution time.

Example1

In this instance, we define two variables where one has a global scope and the other has a local scope, both sharing the same name.

The output displays that the locally scoped variable takes precedence over the global variable in terms of value assignment.

Example

<!DOCTYPE html> 

<html>

<head> 

</head>

<body>

<script>

var $var12 = 200;   

  

function example() {    

    var $var12 = 300;   

    document.write("Inside example() function = " + $var12);   

}   

document.write("Outside example() function = "  + $var12);  

document.write("<br>");

example(); 

</script>



</body>

</html>

Output

Input Required

This code uses input(). Please provide values below: