Labs ICT
Pro Login

Scope

2 min read | JavaScript Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Global Scope

Variables declared outside any function or block are in the global scope and accessible everywhere.

const globalVar = "I am global";

function showGlobal() {
  console.log(globalVar); // accessible here
}

showGlobal(); // I am global
console.log(globalVar);  // I am global

Function Scope

Variables declared with var inside a function are scoped to that function and not visible outside.

function myFunction() {
  var secret = "hidden";
  console.log(secret); // "hidden"
}

myFunction();
// console.log(secret); // ReferenceError

Block Scope with let and const

Both let and const are block-scoped, meaning they exist only within the nearest set of curly braces.

if (true) {
  let blockLet = "I exist only here";
  const blockConst = "Me too";
  console.log(blockLet); // works
}
// console.log(blockLet);  // ReferenceError
// console.log(blockConst); // ReferenceError

Scope Chain

JavaScript looks up variables through nested scopes, from innermost to outermost.

const outer = "outer";

function middle() {
  const inner = "inner";
  function deep() {
    const deepest = "deepest";
    console.log(deepest); // deepest
    console.log(inner);   // inner (from parent)
    console.log(outer);   // outer (from grandparent)
  }
  deep();
}

middle();

var vs let vs const

var is function-scoped and hoisted. let and const are block-scoped and not initialized until declared (temporal dead zone).

function scopeDemo() {
  if (true) {
    var varX = "I leak out";
    let letY = "I stay inside";
  }
  console.log(varX); // "I leak out"
  // console.log(letY); // ReferenceError
}

scopeDemo();