Ankaj Gupta
February 03, 2019

Variable Scope in JavaScript

What is Scope in JavaScript?

Scope in JavaScript defines the accessibility of variables, functions, and objects. It determines the lifetime and visibility of a variable. Every time we create a function or a block {}, we create a new scope.

Understanding Variable Scope

Variable scope is the accessibility of variables, objects, and functions in a particular part of your code during runtime. In other words, scope determines the visibility of JavaScript variables and other resources in areas of your code.

Scope is how a computer keeps track of all variables in a program. It refers to the specific environment where a JavaScript variable is accessible and can be used.

Important: In JavaScript, there are 3 types of variable scope:

  1. Global variable: Declared globally (outside any function)
  2. Local variable: Declared locally (inside any function or block)
  3. Lexical variable: Ability of an inner function to access the scope of an outer function

Note: Global variables can be accessed from anywhere in a JavaScript program.

1. Global Variable

A global variable has global scope, meaning it can be defined anywhere in your code. JavaScript global variables are declared outside the function or declared with the window object and can be accessed and modified from anywhere in the code.

Memory: Global variables are always stored in memory. Even after function execution finishes, they remain accessible from anywhere in JavaScript code.

Example 1: Variable Defined Outside Any Function

Create a global variable by declaring it outside any function:

<script>
    //Initialize a global variable
    var data = 100; //'data' is global variable
    
    function myFunction(){
        document.writeln(data); // here can use data
    }
    
    function display(){
        // can also use data
    }
    
    myFunction(); //calling JavaScript function
</script>

Example 2: Access Variable via Window Object

When declared outside a function, the variable is added to the window object internally:

<script>
    var data = 100;
    
    function display() {
        document.writeln(data);
        document.writeln(window.data); // Access via window object
    }
    
    display(); //calling JavaScript function
</script>

Example 3: Declare Global Variable Inside Function

To declare global variables inside a function, use the window object:

<script>
    function myFunction(){
        //declaring global variable by window object
        window.data = 100;
    }
    
    function display(){
        //accessing global variable from other function
        document.writeln(window.data);
    }
    
    myFunction(); //calling JavaScript function
</script>

Example 4: Auto Global Scope (Not Recommended)

If you declare variables without the var keyword, they are automatically considered global scope:

<script>
    function display() {
        //variable declaring without specify keyword
        data = 100;
        document.writeln(data);
    }
    
    display();
    document.writeln(data); //data is accessible here
</script>

Output:

100
100

⚠️ Warning: Always use var, let, or const to avoid accidental global variables.

2. Local Variable

A variable declared inside a function is a local variable. Local variables have local scope and can't be accessed or modified outside the function declaration. Function parameters are always local to that function.

Memory: Local variables are stored in the stack frame within the function. They are created when function starts execution and removed from memory once execution is complete.

In JavaScript, there are 2 kinds of local scope:

  1. Function scope
  2. Block scope

Function Scope

Variables declared inside a function are known as function scope. In JavaScript, each function creates a new scope. When you declare a variable within a function, it can only be accessed within that function. When you exit the function, the variable is destroyed.

<script>
    function myFunction() {
        var data = "I am local scope";
        document.write(data);
    }
    
    myFunction();
    document.write(data); //Uncaught ReferenceError: data is not defined
</script>

Note: JavaScript functions have their own scope, but block scopes such as if/switch conditions or for/while loops do not create new scopes with var.

Block Scope

A block scope variable is similar to a function scope but is limited to a block instead of a function. A block is separated by curly braces {}.

ES6: ES6 introduced const and let variables. Unlike var, they allow us to scope to a block of code (the nearest pair of curly braces).

Example: Block Scope with let

<script>
    for(let i = 0; i <= 5; i++ ) {
        //write something
    }
    document.write(i); //i can not be used here
</script>

Example: Block with let/const

<script>
    {
        let x = 2;
    }
    document.write(x); //x can not be used here
</script>

Output:

ReferenceError: x is not defined

Example: Block with var (No Block Scope)

Variables declared with var keyword inside a block {} can be accessed from outside the block:

<script>
    {
        var x = 2;
    }
    document.write(x); //x can be used here
</script>

Output:

2

Important: let and const are block scoped variables. Block scope does NOT apply to var.

Key Points About Block Scope

  • • Before ES2015, JavaScript did not have Block Scope
  • • Variables declared inside a block {} with let/const cannot be accessed from outside the block
  • • Block statements like for/while loops or if/switch conditions do NOT create new scope with var

3. Lexical Scope

Lexical Scope (also known as Static scope or Nested scopes) literally means that scope is determined at lexing time (generally referred to as compiling) rather than at runtime.

Static Scope: When a function is defined inside another function, the inner function has access to the outer function's variables. This behavior is called lexical scoping.

Syntax: Nested Scopes

<script>
    function myFunction() {
        //local function scope
        function innerFunction() {
            //nested local function scope
        }
    }
</script>

Example: Lexical Scope

<script>
    function myFunction() {
        const outer = "I'm outer function!";
        
        function innerFunction() {
            const inner = "I'm inner function!";
            document.writeln(outer); // Can access outer variable
            document.writeln(inner);
        }
        
        innerFunction();
    }
    
    myFunction();
</script>

Output:

I'm outer function!
I'm inner function!

Why is Scope Important?

Security

Variables can be accessed only from specific areas of code, preventing unintended modifications.

Avoid Collisions

Reduces namespace collisions when two or more variables share a common name.

Code Organization

Helps organize and structure code logically with proper encapsulation.

Scope Comparison

Scope Type var let const
Global ✅ Yes ✅ Yes ✅ Yes
Function ✅ Yes ✅ Yes ✅ Yes
Block ❌ No ✅ Yes ✅ Yes
Lexical ✅ Yes ✅ Yes ✅ Yes

Best Practices

✅ Do's

  • • Use let and const instead of var
  • • Declare variables in the smallest scope possible
  • • Avoid global variables when possible
  • • Use meaningful variable names
  • • Understand lexical scoping for closures

❌ Don'ts

  • • Don't use var in modern JavaScript
  • • Avoid creating global variables unintentionally
  • • Don't rely on block scope with var
  • • Avoid variable name collisions
  • • Don't ignore scope when debugging

Summary

Understanding scope is fundamental to JavaScript programming. Scope determines where variables are accessible and how long they exist in memory:

  1. Global Scope: Variables accessible throughout the entire program
  2. Local Scope: Variables accessible only within their function or block
  3. Lexical Scope: Inner functions can access outer function variables

Always use let and const for better scope control and avoid unintended side effects. Understanding scope helps write secure, maintainable, and bug-free code.

JavaScript

Join the discussion

Comments

0 comments

No comments yet — be the first to share your thoughts.

Related Posts