Lesson 59 +15 XP

Scope and Hoisting

Scope and Hoisting

Scope decides where a variable is visible. Hoisting is how declarations move to the top.

Global scope

Variables declared outside any function are global, visible everywhere:

let globalVar = "I am everywhere";

Local scope

Variables declared inside a function are local, visible only there:

function greet() {
  let local = "only inside";
  console.log(local);
}
console.log(local); // Error: not defined

Block scope with let and const

let and const are block scoped, so they only exist inside their { }:

if (true) {
  let x = 10;
}
console.log(x); // Error

Hoisting

Function declarations and var variables are moved to the top of their scope. That is why you can call a function before its line:

sayHi(); // works!
function sayHi() {
  console.log("Hi");
}

let and const are not hoisted

Using a let or const before its declaration causes an error.

TL;DR

  • Global variables are visible everywhere.
  • Local variables only exist inside their function.
  • let and const are block scoped.
  • Functions and var are hoisted; let and const are not.