# 16. MEDIUM | Scope in JavaScript

* * *

## Global Scope

Variables and functions declared in the global scope are at the **<mark class="bg-yellow-200 dark:bg-yellow-500/30">highest level</mark>** of your code, outside of any function or block statement.

● **Accessibility**: They can be accessed from any part of the program, including inside functions, loops, and conditional statements.

● **Lifetime**: Global resources persist in memory as long as the program is running (e.g., until the browser window is closed).

```javascript
let message = "Hello, World!"; // global scope
const age = 25; // global scope
var name = 'shubham'; // global scope

function greet() { // global scope
  console.log(message); // Access global variable
}

if (true){
console.log(name); // Access global variable
}

greet(); // Output: Hello, World!
console.log(age); // Output: 25
```

Global scope is further divided into two parts viz. **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Window scope</mark>** and **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Script scope</mark>**.

| **Window Scope** | **Script Scope** |
| --- | --- |
| **Includes:** `var` variables and functions. | **Includes:** `let` and `const` variables. |
| Can be accessed using `window` object as they become properties of `window` object. | Can't be accessed using `window` object |

* * *

## Local Scope

Local scope provides isolation, **<mark class="bg-yellow-200 dark:bg-yellow-500/30">preventing variables and functions</mark>** from being accessed by code outside their defined context. It is further divided into function scope and block scope.

*   **Function Scope**: Variables (`var`, `let`, or `const`) and functions declared inside a function are local to that function and can only be accessed within it.
    

```javascript
function parent() {
  const price = 100; // Local variable (function scope)
  let product = 'bulb'; // Local variable (function scope)
  var isOn = true; // Local variable (function scope)
  
  console.log(price);

  function child() {
    console.log("I am inside parent function.");
  }

  child();
}

parent(); 
/* Output:
100
I am inside parent function.
*/

console.log(price); // Error: price is not defined
console.log(product); // Error: product is not defined
console.log(isOn); // Error: isOn is not defined
child(); // Error: child is not defined
```

*   **Block Scope**: Introduced with ES6, variables declared with `let` and `const` inside a code block (defined by curly braces `{}`), such as in conditional statements or loops, are only accessible within that specific block. Variables declared with `var` do not have block scope.
    

```javascript
if (true) {
  let blockVar = "I'm block-scoped";
  console.log(blockVar); // Works
}

// console.log(blockVar); // Error: blockVar is not defined

if (true) {
  var functionVar = "I escape the block!";
}
console.log(functionVar); // Works! "I escape the block!"
```

● **Lifetime**: Local variables or functions are created when their scope (function or block) is entered and are deleted once the execution of that scope is completed.

* * *

### Final Example

```javascript
let name = 'shubham'; // global scope
const age = 25; // global scope
var subjects = ['math', 'science']; // global scope

function parent() { // global scope
    let a = 'I am parent'; // local (parent) scope
    const b = 25; // local (parent) scope
    var c = true; // local (parent) scope

    function child() { // local (parent) scope
        let a = 'I am parent'; // local (child) scope
        const b = 25; // local (child) scope
        var c = true; // local (child) scope
    }

    child();
}

if (true) {
    let x = 23; // block scope
    const y = 34; // block scope
    var z = 45; // not block scope
}

function addition() { // global scope
    console.log('I do addition.')
}


parent();

addition();
```

* * *

## Lexical Scope

● **Inner Scopes Access Outer Scopes**: A function defined inside another function (a "child" or "inner" scope) has access to variables and other resources declared in its parent (outer) scopes, all the way up to the global scope.

● **Outer Scopes Cannot Access Inner Scopes**: The reverse is not true. An outer function or global scope cannot access variables defined inside a child function. Attempting to do so will result in a `ReferenceError`.

● **Scope Chain**: When a variable is accessed, JavaScript follows a "scope chain". It first looks in the current local scope. If not found, it moves up to the immediate parent scope, and continues this search process upward until it reaches the global scope.

```javascript
var globalVar = "I'm global!"; // Global Scope

function outerFunction() {
  let outerVar = "I'm in outer!"; // Outer Function Scope

  function innerFunction() {
    let innerVar = "I'm in inner!"; // Inner Function Scope
    console.log(globalVar); // Works: Accesses global scope
    console.log(outerVar); // Works: Accesses parent scope
    console.log(innerVar); // Works: Accesses local scope
  }

  innerFunction();
  console.log(innerVar); // ReferenceError: innerVar is not defined
}

outerFunction();
console.log(outerVar); // ReferenceError: outerVar is not defined
```

![](https://cdn.hashnode.com/uploads/covers/679f94da85491cdb2d8e2e57/cd0d1ebb-94c3-4c74-a90b-51328c752555.png align="center")

* * *

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">What happens when we declare and initialize a variable without <code>var</code>, <code>let</code> or <code>const</code> (e.g. name = 'shubham')?</div>
</div>

**Answer:** It goes under Window (Global) scope and becomes property of `window` object and can be accessed anywhere.

* * *

Happy reading!
