# JavaScript Part 2 : Scope & Execution 

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

```javascript
const company = "OpenAI";

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

showCompany();
```

Output

```text
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

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

greet();

// console.log(message);
```

Output

```text
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

```javascript
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

```javascript
const company = "OpenAI";

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

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

    inner();
}

outer();
```

Output

```text
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

```javascript
const language = "JavaScript";

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

    inner();
}

outer();
```

Output

```text
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

```javascript
const name = "Global";

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

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

execute();
```

Output

```text
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

```javascript
let name = "Global";

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

    console.log(name);
}

greet();

console.log(name);
```

Output

```text
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

```javascript
console.log(age);

var age = 20;
```

Output

```text
undefined
```

Internally, JavaScript treats it like:

```javascript
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

```javascript
console.log(name);

let name = "Aditya";
```

Output

```text
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

```javascript
"use strict";

age = 20;
```

Output

```text
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?
