Web Analytics

JavaScript Scope & Closures

Intermediate ~20 min read

What is Scope?

Scope determines the accessibility (visibility) of variables. JavaScript has 3 types of scope:

  • Block scope (let, const)
  • Function scope (var, let, const)
  • Global scope
HTML
CSS
JS

Closures

A closure is a function having access to the parent scope, even after the parent function has closed.

HTML
CSS
JS
Why Closures? Closures make it possible for a function to have "private" variables. The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

Hoisting

Hoisting is JavaScript's default behavior of moving declarations to the top.

x = 5; // Assign 5 to x
var x; // Declare x
// This works because of hoisting
Let and Const are not hoisted in the same way. Using a let variable before it is declared will result in a ReferenceError.

Summary

  • Variables declared with var have function scope.
  • Variables declared with let and const have block scope.
  • Closures allow functions to access variables from an enclosing scope even after it has finished executing.
  • Hoisting moves declarations to the top of the current scope.

Quick Quiz

Which keyword creates a block-scoped variable?

A
var
B
let
C
global
D
function