DEV Community

Sudhakar V
Sudhakar V

Posted on • Edited on

Local and Global Variables in JavaScript

1. Global Variables

A global variable is declared outside of any function and can be accessed from anywhere in the code (inside or outside functions).

Example:

let globalVar = "I am global";

function showGlobal() {
  console.log(globalVar); // Can access globalVar
}

showGlobal();
console.log(globalVar); // Also accessible here
Enter fullscreen mode Exit fullscreen mode

2. Local Variables

A local variable is declared inside a function (or block using let/const) and can only be accessed within that function or block.

Example:

function showLocal() {
  let localVar = "I am local";
  console.log(localVar); // OK
}

showLocal();
// console.log(localVar); // Error: localVar is not defined
Enter fullscreen mode Exit fullscreen mode

Block Scope with let and const

Variables declared with let or const are block-scoped, which means they're only accessible within { } braces.

if (true) {
  let blockVar = "Inside block";
  console.log(blockVar); // OK
}
// console.log(blockVar); //  Error
Enter fullscreen mode Exit fullscreen mode

Note on var

var is function-scoped but not block-scoped.

function testVar() {
  if (true) {
    var x = 10;
  }
  console.log(x); //  Works: x is function-scoped
}
testVar();
Enter fullscreen mode Exit fullscreen mode

Comparison Table

Type Scope Accessible From Keyword
Global Entire script Anywhere var, let, const (outside)
Local Function/Block Only inside its block let, const, var (inside)

Summary

  • Global Variable = Accessible anywhere in the file.
  • Local Variable = Accessible only inside the function or block where it’s declared.

Top comments (0)