Scope
function myFunction() {
var pizzaName = 'Margarita';
// Code here can use pizzaName
}
// Code here can't use pizzaName
Block Scoped Variables
if (isLoggedIn == true) {
const statusMessage = 'Logged in.';
}
// Uncaught ReferenceError...
console.log(statusMessage);
Global Variables
// Variable declared globally
const color = 'blue';
function printColor() {
console.log(color);
}
printColor(); // => blue
let vs var
var is scoped to the nearest function block, and let is scoped to the nearest enclosing block.
let
for (let i = 0; i < 3; i++) {
// This is the Max Scope for 'let'
// i accessible ✔️
}
// i not accessible ❌
var
for (var i = 0; i < 3; i++) {
// i accessible ✔️
}
// i accessible ✔️