JavaScript Scope & Closures
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
Closures
A closure is a function having access to the parent scope, even after the parent function has closed.
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 variable before it is declared will
result in a ReferenceError.
Summary
- Variables declared with
varhave function scope. - Variables declared with
letandconsthave 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?
Enjoying these tutorials?