Member-only story
Mastering JavaScript Variables: let
, const
, and var
Explained in 1 Minute
2 min readNov 19, 2024
JavaScript offers three ways to declare variables: var
, let
, and const
. While they all serve the same purpose, their behavior differs significantly. Here’s a quick guide:
1. var
- Scope: Function-scoped, meaning it’s only accessible within the function where it’s declared.
- Hoisting: Gets hoisted to the top of its scope but initialized as
undefined
. - Use Case: Mostly used in older codebases. Avoid using it in modern JavaScript.
function example() {
var x = 10;
if (true) {
var x = 20; // Same variable redeclared
console.log(x); // 20
}
console.log(x); // 20
}
2. let
- Scope: Block-scoped, meaning it’s accessible only within the
{}
block it’s defined in. - Hoisting: Also hoisted, but not initialized (accessing it before declaration causes an error).
- Use Case: Ideal for variables that may need to be reassigned.
let y = 10;
if (true) {
let y = 20; // New variable in block scope
console.log(y); // 20
}
console.log(y); // 10
3. const
- Scope: Block-scoped, like
let
. - Hoisting: Same as, but must be…