JavaScript Scope

Scope decides where a variable can be used. A variable made in one place may not be visible in another place.


Global and local scope

let globalVar = "global";

function test() {
  let localVar = "local";
  console.log(globalVar);
  console.log(localVar);
}

test();
console.log(localVar);
Output of the above program is

global
local
ReferenceError: localVar is not defined

A variable declared outside every function is global, and can be used everywhere. A variable declared inside a function is local, and exists only in that function.


Block scope

A block is the code inside curly braces { }, for example in an if or a loop. let and const stay inside the block. var ignores blocks.

if (true) {
  let a = 1;
  var b = 2;
}

console.log(b);
console.log(a);
Output of the above program is

2
ReferenceError: a is not defined

Note: This is one big reason to use let and const, and to avoid var.

Hoisting

JavaScript moves declarations to the top of their scope before running the code. For var the variable exists, but its value is undefined until the line is reached.

console.log(x);
var x = 5;
console.log(x);
Output of the above program is

undefined
5

let and const are also hoisted, but you cannot use them before the line where they are declared. This gap is called the temporal dead zone.

console.log(y);
let y = 5;
Output of the above program is

ReferenceError: Cannot access 'y' before initialization

Function declarations are hoisted completely, so you can call them before they appear in the code.


Nested scope

An inner function can use the variables of its outer function, but not the other way round. This is what makes closures work.

function outer() {
  let message = "Hi";
  function inner() {
    console.log(message);   // can see message
  }
  inner();
}
outer();
Output of the above program is

Hi


Summary

  • Global variables are visible everywhere, local variables only in their function.
  • let and const are block scoped, var is function scoped.
  • Declare variables before you use them.
  • Next: JavaScript Data Types.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.