let Declaration
let variableName = value;let score = 0;
score = 10;
console.log(score);10Note Block-scoped. Cannot be re-declared in the same scope. Preferred for values that change.
JavaScript · 10 entries
let variableName = value;let score = 0;
score = 10;
console.log(score);10Note Block-scoped. Cannot be re-declared in the same scope. Preferred for values that change.
const variableName = value;const API_URL = "https://api.example.com";
const cart = ["apple"];
cart.push("banana"); // allowed
console.log(cart);["apple", "banana"]Note Block-scoped. Must be initialized at declaration. The binding is immutable, but object/array contents can still change.
var variableName = value;function demo() {
if (true) {
var leaked = "visible outside block";
}
console.log(leaked);
}
demo();"visible outside block"Note Function-scoped, not block-scoped. Hoisted to the top of the function. Avoid in modern code -- use let or const instead.
const [a, b, ...rest] = array;const rgb = [30, 120, 255];
const [red, green, blue] = rgb;
console.log(green);
const [first, , third] = ["a", "b", "c"];
console.log(first, third);120
"a" "c"Note Use commas to skip elements. Works with any iterable, not just arrays.
const { key1, key2: alias } = object;const user = { name: "Lina", role: "admin", id: 42 };
const { name, role, id: userId } = user;
console.log(name, userId);"Lina" 42Note Use colon to rename. Combine with defaults: const { theme = "light" } = settings;
const { outer: { inner } } = obj;const response = {
data: { user: { name: "Kai", scores: [95, 88] } }
};
const { data: { user: { name, scores: [latest] } } } = response;
console.log(name, latest);"Kai" 95Note Deeply nested destructuring can hurt readability. Consider extracting in steps for complex structures.
const merged = [...arr1, ...arr2];
const merged = { ...obj1, ...obj2 };const defaults = { theme: "light", lang: "en" };
const prefs = { theme: "dark", fontSize: 16 };
const config = { ...defaults, ...prefs };
console.log(config);{ theme: "dark", lang: "en", fontSize: 16 }Note Later properties overwrite earlier ones. Only performs a shallow copy -- nested objects are still shared by reference.
function fn(...args) {}function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(5, 10, 15));30Note Rest must be the last parameter. Unlike the old arguments object, rest gives you a real Array with all array methods.
const { key = defaultValue } = obj;
const [a = defaultValue] = arr;const { host = "localhost", port = 3000 } = { port: 8080 };
console.log(host, port);"localhost" 8080Note Defaults only apply when the value is undefined, not when it is null or other falsy values.
[a, b] = [b, a];let x = "hello";
let y = "world";
[x, y] = [y, x];
console.log(x, y);"world" "hello"Note No temporary variable needed. Works with any number of variables: [a, b, c] = [c, a, b];