J

JavaScript Tutorial

Clean • Professional

JavaScript Scope

1 minute

JavaScript Scope

Scope defines where a variable can be accessed in your code.

In JavaScript, there are three main types of scope:

learn code with durgesh images

1. Global Scope

  • Variables declared outside any function or block.
  • Accessible everywhere in your code.
  • Can cause naming conflicts if used carelessly.

Example:

var globalVar = "I'm global";

function test() {
  console.log(globalVar); // I'm global
}

test();
console.log(globalVar); // I'm global

2. Local (Function) Scope

  • Variables declared inside a function (var, let, or const).
  • Accessible only within that function.
  • Not visible outside the function.

Example:

function myFunction() {
  var localVar = "I'm local";
  console.log(localVar); // I'm local
}

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

3. Block Scope

  • Introduced in ES6 with let and const.
  • Variables declared inside a block {} (like in if, for, or while) are limited to that block.
  • var does not follow block scope, which can cause unintended behavior.

Example:

if (true) {
  let blockVar = "I'm block-scoped";
  var varVar = "I'm not block-scoped";
  console.log(blockVar); // I'm block-scoped
}

// console.log(blockVar);  Error: blockVar is not defined
console.log(varVar); // I'm not block-scoped (leaks out)

Summary

Scope TypeDeclared WithAccessible WhereNotes
Globalvar, let, const (outside functions/blocks)EverywhereCan cause conflicts
Local (Function)var, let, const (inside functions)Inside the functionIsolated from outside
Blocklet, constInside {} onlySafer and modern practice


Article 0 of 0