JavaScript: var, let, and const
If you're a JavaScript developer, you probably use var, let, or const in your code. But do you really know what's happening under the hood? Let’s break it down! ??
?? var – The Old Way
Before ES6, var was the only way to declare variables in JavaScript. But it comes with some quirks:
?? Hoisting: var declarations are hoisted to the top but without initialization.
?? Function scope: If declared inside a function, the variable exists only within that function. Otherwise, it becomes global.
?? Can be redeclared without errors.
console.log(name); // undefined (no error!)
var name = "David";
console.log(name); // "David"
if (true) {
var age = 30;
}
console.log(age); // 30 (accessible outside the block) ??
? let – A Safer Alternative
With ES6, let was introduced to fix some issues with var:
?? Block scope: The variable exists only within the {} block where it was declared.
?? Cannot be redeclared in the same scope.
?? Hoisted but uninitialized (causing a ReferenceError if accessed too early).
console.log(color); // ReferenceError ?
let color = "blue";
This happens because let variables are in the Temporal Dead Zone (TDZ) until they are initialized.
领英推荐
??? const – For Constant Values
ES6 also introduced const, which behaves like let but with additional restrictions:
?? Must be initialized when declared.
?? Cannot be reassigned (but objects and arrays are still mutable).
?? Follows the same block scope rules as let.
const pi = 3.14; pi = 3.1415; // TypeError ?
However, objects and arrays remain mutable:
const person = { name: "David" };
person.name = "Silva"; // ? Allowed!
console.log(person.name); // "Silva"
If you truly want to make an object immutable, use Object.freeze():
const user = Object.freeze({ name: "David" });
user.name = "Silva"; // ? No effect
console.log(user.name); // "David"