Skip to main content

Command Palette

Search for a command to run...

JavaScript Part 2 : Scope & Execution

Updated
6 min readView as Markdown
A

Hi there! I'm Aditya, a passionate Full-Stack Developer driven by a love for turning concepts into captivating digital experiences. With a blend of creativity and technical expertise, I specialize in crafting user-friendly websites and applications that leave a lasting impression. Let's connect and bring your digital vision to life!

JavaScript's execution model revolves around scope and execution context. Understanding how variables are accessed, how JavaScript resolves them, and how hoisting works is one of the most frequently tested topics in JavaScript interviews.

This guide provides a quick revision of the essential concepts.

Topics Covered

  • Global Scope

  • Function Scope

  • Block Scope

  • Scope Chain

  • Lexical Scope

  • Dynamic Scope (Comparison)

  • Variable Shadowing

  • Hoisting

  • Temporal Dead Zone (TDZ)

  • Strict Mode

Global Scope

Global Scope is the outermost scope in JavaScript. Variables declared outside any function or block belong to the global scope and can be accessed from anywhere in the program.

When JavaScript starts executing a file, it creates a global execution context. Any variable declared outside a function or block becomes part of the global scope.

Example

const company = "OpenAI";

function showCompany() {
    console.log(company);
}

showCompany();

Output

OpenAI

Important Points

  • Accessible throughout the program.

  • Created when JavaScript starts execution.

  • Avoid creating too many global variables as they can lead to naming conflicts.

Function Scope

Variables declared inside a function can only be accessed within that function.

Every function creates its own scope. Variables inside a function are private to that function.

Example

function greet() {
    let message = "Hello";
    console.log(message);
}

greet();

// console.log(message);

Output

Hello

The last line throws a ReferenceError because message exists only inside the function.

Important Points

  • Every function creates a new scope.

  • Variables inside a function are inaccessible from outside.

  • var follows function scope.

Block Scope

Variables declared using let and const are accessible only within the block ({}) where they are declared.

A block can be an if statement, for loop, while loop, or any pair of curly braces.

Example

if (true) {
    let age = 20;
    const city = "Delhi";
}

// console.log(age);
// console.log(city);

Both statements outside the block throw a ReferenceError.

Important Points

  • Only let and const are block scoped.

  • var ignores block scope.

  • Helps prevent accidental access to variables.

Scope Chain

A Scope Chain is the process JavaScript uses to search for a variable when it is accessed.

JavaScript first looks in the current scope. If the variable is not found, it moves to the parent scope.

This continues until the global scope is reached. If the variable is still not found, a ReferenceError is thrown.

Example

const company = "OpenAI";

function outer() {
    const team = "AI";

    function inner() {
        console.log(company);
        console.log(team);
    }

    inner();
}

outer();

Output

OpenAI
AI

Important Points

  • Search starts from the current scope.

  • Moves outward toward the global scope.

  • Never searches child scopes.

Lexical Scope

Lexical Scope means a function can access variables from the scope where it was defined.

The scope of a function is determined by its position in the source code, not by where it is called.

Example

const language = "JavaScript";

function outer() {
    function inner() {
        console.log(language);
    }

    inner();
}

outer();

Output

JavaScript

Important Points

  • Scope is decided when code is written.

  • JavaScript uses lexical scoping.

  • Closures are based on lexical scope.


Dynamic Scope (Comparison)

Dynamic Scope means a function accesses variables based on where it is called rather than where it is defined.

JavaScript does not support dynamic scoping. It always uses lexical scope.

Example

const name = "Global";

function greet() {
    console.log(name);
}

function execute() {
    const name = "Local";
    greet();
}

execute();

Output

Global

If JavaScript used dynamic scope, the output would have been "Local".

Important Points

  • JavaScript does not support dynamic scope.

  • Variable lookup is based on where the function is defined.

Variable Shadowing

Variable Shadowing occurs when a variable declared in an inner scope has the same name as a variable in an outer scope.

The inner variable hides (or shadows) the outer variable within that scope.

Example

let name = "Global";

function greet() {
    let name = "Local";

    console.log(name);
}

greet();

console.log(name);

Output

Local
Global

Important Points

  • Inner variables take precedence.

  • Outer variable remains unchanged.

  • Commonly used inside functions and blocks.

Hoisting

Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the creation phase of the execution context.

Only declarations are hoisted, not initializations.

  • var is hoisted and initialized with undefined.

  • let and const are hoisted but remain uninitialized until their declaration executes.

Example

console.log(age);

var age = 20;

Output

undefined

Internally, JavaScript treats it like:

var age;

console.log(age);

age = 20;

Important Points

  • Declarations are hoisted.

  • Initializations are not hoisted.

  • Function declarations are fully hoisted.

Temporal Dead Zone (TDZ)

The Temporal Dead Zone (TDZ) is the period between entering a scope and initializing a let or const variable.

During this period:

  • Memory has been allocated.

  • The variable exists.

  • The variable cannot be accessed.

Trying to access it results in a ReferenceError.

Example

console.log(name);

let name = "Aditya";

Output

ReferenceError

Important Points

  • Applies only to let and const.

  • Starts when the scope is entered.

  • Ends when the variable is initialized.

  • Prevents accidental access before initialization.

Strict Mode

Strict Mode is a special JavaScript mode that enables stricter parsing and error handling, helping developers write safer and more predictable code.

Strict Mode is enabled by adding "use strict"; at the beginning of a script or function.

It prevents many common mistakes that JavaScript normally allows.

Example

"use strict";

age = 20;

Output

ReferenceError: age is not defined

Without Strict Mode, JavaScript would create a global variable automatically.

Important Points

  • Enabled using "use strict";

  • Prevents accidental global variables.

  • Disallows duplicate parameter names.

  • Makes silent errors throw exceptions.

  • Recommended for writing modern JavaScript.

Interview Questions

  1. What is the difference between Global Scope, Function Scope, and Block Scope?

  2. Explain the Scope Chain with an example.

  3. What is Lexical Scope?

  4. Does JavaScript support Dynamic Scope?

  5. What is Variable Shadowing?

  6. What is Hoisting? Are variables initialized during hoisting?

  7. What is the Temporal Dead Zone?

  8. Why does var not have a TDZ?

  9. What is Strict Mode? Why is it used?

  10. What is the difference between Hoisting and the Temporal Dead Zone?