Rilasciato · in miglioramento
Guida a JavaScript · 2/6
Per ora questo capitolo è disponibile solo in inglese.
This chapter covers the syntax you will read and write every day: declaring variables, writing functions, branching and looping, template literals, and the destructuring and spread syntax that shows up all over modern JavaScript.
There are three ways to declare a variable. Reach for const by default and switch to let only when the variable must be reassigned. var still appears in older code, but there is rarely a reason to write it today.
| Keyword | Reassignable | Scope | Notes |
|---|---|---|---|
const | No | Block | The default choice |
let | Yes | Block | For values that change |
var | Yes | Function | Hoisting makes it confusing |
const greeting = "Hello";
let count = 0;
count += 1;
if (true) {
let inside = "block";
var leaked = "function";
}
console.log(leaked); // "function": var escapes the block
// console.log(inside); // ReferenceError: let stays inside it
const user = { name: "Sam" };
user.name = "Alex"; // allowed: const blocks reassignment, not mutationconst does not freeze an object. If you need the contents locked too, use Object.freeze().
A function declaration can be called from anywhere in its scope. Arrow functions are shorter and shine as callbacks. Both support default values and rest parameters.
function add(a, b) {
return a + b;
}
// a single-expression body needs no braces or return
const square = (x) => x * x;
const makeUser = (name) => ({ name, createdAt: Date.now() }); // wrap object literals in parentheses
function greet(name = "guest", ...tags) {
return `${name} (${tags.join(", ")})`;
}
console.log(add(2, 3)); // 5
console.log(square(4)); // 16
console.log(greet()); // "guest ()"
console.log(greet("Kim", "vip", "new")); // "Kim (vip, new)"Arrow functions also differ in how they treat this; chapter 6 explains why that matters.
Compare with === and !==. The loose == converts types first, which is how 0 == "" ends up true.
const fruits = ["apple", "pear", "grape"];
for (const fruit of fruits) {
console.log(fruit);
}
for (let i = 0; i < fruits.length; i += 1) {
if (fruits[i] === "pear") continue;
console.log(i, fruits[i]);
}
const score = 82;
const grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
switch (grade) {
case "A":
console.log("Excellent");
break;
case "B":
console.log("Good");
break;
default:
console.log("Keep going");
}
// optional chaining and nullish coalescing
const config = { server: { port: 0 } };
const port = config.server?.port ?? 3000; // 0, because ?? only replaces null/undefined
const host = config.server?.host ?? "localhost";for...of walks the values of an array; for...in walks the keys of an object, so prefer for...of for arrays. When supplying defaults, ?? keeps legitimate values like 0 or "" that || would throw away.
Backtick strings accept embedded expressions with ${...} and can span several lines.
const item = "keyboard";
const price = 45;
const message = `The ${item} costs $${price.toFixed(2)}.
With shipping: $${(price + 5).toFixed(2)}`;
console.log(message);Destructuring pulls values out of objects and arrays into variables. You can rename and supply defaults on the way, and it works directly in function parameters.
const order = { id: 17, customer: "Riley", items: ["pen", "notebook"], note: undefined };
const { id, customer: buyer, note = "no note" } = order;
console.log(id, buyer, note); // 17 "Riley" "no note"
const [first, second] = order.items;
// swap two variables
let a = 1;
let b = 2;
[a, b] = [b, a];
function printOrder({ id, items }) {
console.log(`#${id}: ${items.length} items`);
}
printOrder(order);Putting ... in front of an array or object expands its contents. It is the usual way to copy or merge without touching the original. Keep in mind the copy is shallow: nested objects are still shared.
const base = [1, 2, 3];
const more = [...base, 4, 5]; // [1, 2, 3, 4, 5]
const defaults = { theme: "light", lang: "en" };
const settings = { ...defaults, theme: "dark" }; // later keys win
console.log(Math.max(...base)); // 3
console.log(defaults.theme); // "light", untouchedconst, use let for reassignment, and avoid var.===; reach for ?. and ?? when a value may be missing.
0 commenti
Accedi · Accedi per lasciare un commento.
Scrivi tu il primo commento.