Master arrow syntax, block scope, and closures, then build dynamic strings with template literals.
Open this lesson in KodokonArrow functions are everywhere in modern code: map and filter callbacks, event listeners, promises. Their strength: a compact syntax with an implicit return when the body fits in a single expression. As soon as you open curly braces, the return becomes mandatory again.
const double = (n) => n * 2;
const isAdult = (user) => user.age >= 18;
const buildUser = (name) => ({ name, active: true });
const sum = (a, b) => {
const total = a + b;
return total;
};
console.log(double(21)); // 42
console.log(buildUser("Ana").active); // trueScope determines where a variable is visible. With let and const, a variable declared inside a block (if, for, curly braces) only exists within that block. Another essential mechanism: a function keeps access to the variables of the scope where it was created, even after that scope has ended. This is a closure, and it's what makes counters, caches, and state managers work.
function createCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2Template literals, delimited by backticks, are a much better alternative to concatenation. You inject an expression with ${...}, and line breaks are preserved as-is, which is ideal for building messages or HTML fragments.
const user = { firstName: "Nadia", cartCount: 3 };
const message = `Hello ${user.firstName}, you
have ${user.cartCount} items in your cart.`;
console.log(message);let inside an if block accessible after that block?