JavaScript Scope – Global vs Local

In JavaScript, scope determines where variables and functions are accessible in your code. There are two main types:

  • Global Scope – Accessible anywhere in your code.
  • Local Scope – Accessible only inside the function or block where it's defined.

 Global Scope

A variable declared outside any function is global. It can be accessed and modified from anywhere in your script.

 Example: Global Variable

var userName = "Bill"; // Global

function modifyUserName() {
    userName = "Steve"; // Changes the global variable
}

function showUserName() {
    alert(userName);
}

alert(userName);     // Output: "Bill"
modifyUserName();
showUserName();      // Output: "Steve"
Key Point: Global variables can be accessed and changed by any function.

 Caution: Accidental Globals

If you assign a value to a variable without using varlet, or const inside a function, it becomes a global variable by mistake.

function createUserName() {
    userName = "Bill"; // No declaration keyword — becomes global!
}

createUserName();
alert(userName); // Output: "Bill"
Issue: If createUserName() isn’t called first, userName doesn’t exist — causing an error.

 Local Scope

Variables declared inside a function using varlet, or const are local. They can't be accessed outside that function.

Example: Local Variable

function createUserName() {
    var userName = "Bill"; // Local
}

function showUserName() {
    alert(userName); // Error: userName is not defined
}

createUserName();
showUserName(); //  Error
Key Point: Local variables exist only within their function.

Local vs Global with Same Name

A local variable can have the same name as a global one. In that case, the local version takes precedence inside the function.

Example: Shadowing

var userName = "Bill"; // Global

function showUserName() {
    var userName = "Steve"; // Local (shadows global)
    alert(userName); // Output: "Steve"
}

showUserName();
alert(userName); // Output: "Bill"
Key Point: Local variables override globals inside their scope but don't affect them outside.

 Block Scope (let and const)

Unlike var, the let and const keywords are block-scoped — they only exist within the { } they are declared in.

Example: Block Scope

function testBlockScope() {
    if (true) {
        let myVar = 22;
        alert(myVar); // Output: 22
    }

    alert(myVar); //  Error: myVar is not defined
}

testBlockScope();
Note: var ignores block scope, but let and const respect it.

Points :

  •  Global variables are accessible throughout the program.
  • Local variables exist only within their function or block.
  • Omitting varlet, or const inside functions creates accidental globals.
  • Local and global variables can share names but won’t interfere with each other.
  • Prefer let and const for safer, block-scoped variables.