JavaScript flashcards
10 cards. Answer in your head, flip, and be honest with yourself.
0Still learning1 / 10Know0
var vs let vs const#
Scope
js
function example() {
var a = 1; // function-scoped
let b = 2; // block-scoped
const c = 3; // block-scoped
if (true) {
var a = 10; // same variable - overwrites!
let b = 20; // new variable - only inside this block
console.log(b); // 20
}
console.log(a); // 10 - was overwritten
console.log(b); // 2 - untouched
}Hoisting
js
console.log(a); // undefined - hoisted but not initialized
console.log(b); // ReferenceError - temporal dead zone
var a = 1;
let b = 2;Reassignment
js
var x = 1; x = 2; // ok
let y = 1; y = 2; // ok
const z = 1; z = 2; // Error - cannot reassign
// const with objects - reference is locked, contents are not
const user = { name: 'Alice' };
user.name = 'Bob'; // ok
user = {}; // ErrorComparison
var | let | const | |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (undefined) | TDZ | TDZ |
| Reassign | Yes | Yes | No |
| Re-declare | Yes | No | No |
Rule: use
constby default,letwhen you need to reassign, never usevar.
space flip · ← → move · 1 still learning · 2 know it