Page Content

Posts

What is the Local & Global Scope in JavaScript with Example

Scopes: Local and Global Scope in JavaScript

The accessibility of variables, functions, and other identifiers in your code is controlled by the fundamental idea of scope. It outlines the sections of your software that are deemed “in scope” or usable by an identifier.

The scope gives the JavaScript Engine the guidelines it needs to locate variables by their identification name. It’s a component of how the Engine manages and accesses variables in conjunction with the Compiler and Scope.

Essentially, scope establishes the variables’ lifetime and visibility. “In scope” refers to the area of the program code where a variable is defined. Since variables are necessary for handling and storing data, our programs would be far more constrained without scope.

There are various scope types available in JavaScript, including:

  1. Global Scope: The broadest scope is the global scope. You can access variables declared in the global scope from anywhere in your JavaScript code. A variable becomes a global variable if a value is assigned to it inside of a function without the use of a declaration keyword (let, var, or const). This is generally prohibited in order to prevent “polluting the global namespace” and may result in unexpected behaviour.
  2. Function Scope: Local variables are those declared inside a function with var. Function parameters are only available within the body of the function and have function scope as well. These function-scoped variables are usually no longer available after the function has completed running.
  3. var declared inside a function “pierces through” the function’s code blocks ({}), causing it to be function-scoped as opposed to block-scoped.
  4. Block Scope: Code blocks encapsulated in curly braces {} are linked to this type of scope. Block scope applies to variables specified with let or const. This indicates that they can only be accessed within the block in which they are declared and any nested blocks that are part of it. Block scopes can also be produced using loops. This is a significant distinction from var, which lacks block scope.

Nested Scope and the Scope Chain: Scopes can be nested inside each other. The JavaScript Engine uses a particular lookup technique when it wants to locate a variable (a process known as variable resolution). It begins by searching the immediate, innermost scope for the variable. The Engine searches the next contained (outer) scope if the variable is not found there, and so on until it reaches the global scope. The scope chain is the name given to this hierarchical lookup structure.

let outerVariable = “I’m in the outer scope”; // Global scope
function outerFunction() {
let innerVariable = “I’m inside outerFunction”; // outerFunction’s scope
console.log(outerVariable); // Can access outer scope variable

function innerFunction() { // Nested function
let deepestVariable = “I’m in the innermost scope”; // innerFunction’s scope
console.log(outerVariable); // Can access variables from outer scopes
console.log(innerVariable); // Can access variables from outer scopes
console.log(deepestVariable); // Can access its own scope variable
}

innerFunction();
// console.log(deepestVariable); // ReferenceError: deepestVariable is not defined (outside innerFunction scope)
}

outerFunction();
// console.log(innerVariable); // ReferenceError: innerVariable is not defined (outside outerFunction scope)

JavaScript’s Lexical Scope, also known as Static Scope, is characterised by this behaviour. According to lexical scope, the scope of variables is determined by the physical writing and nesting of functions and blocks code. In order to clarify how this search operates, the authors also discuss the theoretical idea of a Lexical Environment, which has a reference to its external environment and internally holds variables.

Local and Global Scope in JavaScript

Variables defined outside of any function or code block are referred to as having global scope. After they are defined, these global variables are accessible and usable across the entire application. Global variables are those that are declared at the top level of a script with var.

On the other hand, a function declares local variables. They only apply to the function for which they are defined. Local variables are also applied to function parameters. Moreover, variables declared inside blocks using let and const have local (block-specific) scope. Within its scope, the local variable takes precedence over the global one if they have the same name. This effectively hides the global variable.

Here is an example demonstrating both:

let programName = “My App”; // Global scope

function displayInfo() {
let programName = “Module A”; // Local scope, shadows global
console.log(“Inside function:”, programName); // Accessible local variable
}

displayInfo();
console.log(“Outside function:”, programName); // Accessible global variable

Writing code that is clear, maintainable, and free of errors requires an understanding of scope. In accordance with the “Least Privilege” approach, you can avoid name conflicts and guarantee that variables are only used where intended by limiting where they are accessible. In contemporary JavaScript, let and const are typically preferred over var for block scope since they reduce variable visibility and prevent unexpected behaviour. The variables themselves are similar to “containers” or “named storage” that contain values.

Index