Variables y tipos const · let Constante y variable de bloque (evita var) typeof x "number", "string", "boolean", "undefined", "object", "function" === · !== Comparar sin conversión de tipos Falsy false, 0, "", null, undefined, NaN a ?? b · a?.b Valor por defecto si null/undefined · acceso seguro `Hola ${nombre}` Plantilla de texto Number("3") · parseInt("3px", 10) Convertir a número 0.1 + 0.2 !== 0.3 Decimales en coma flotante: redondea al mostrar
Tema: Fundamentos de JavaScript Arrays const precios = productos.map(p => p.precio); const caros = productos.filter(p => p.precio > 20); const total = productos.reduce((acc, p) => acc + p.precio, 0); const uno = productos.find(p => p.id === 3); productos.some(p => p.agotado); productos.every(p => p.precio > 0); [...a, ...b]; const [primero, ...resto] = lista; lista.toSorted((a, b) => a.precio - b.precio); // sin mutar Object.groupBy(productos, p => p.categoria); Tema: Objetos Predefinidos y BOM Objetos y clases const { nombre, edad = 18 } = persona; // desestructurar const copia = { ...persona, ciudad: "Cádiz" }; Object.entries(obj).forEach(([k, v]) => console.log(k, v)); class Cuenta { #saldo = 0; // privado static creadas = 0; constructor(titular) { this.titular = titular; Cuenta.creadas++; } get saldo() { return this.#saldo; } ingresar(x) { if (x <= 0) throw new RangeError("Importe"); this.#saldo += x; } } class Ahorro extends Cuenta { constructor(t) { super(t); } } Tema: Funciones, Objetos y Clases Funciones y this function f() {} Declaración: se puede usar antes (hoisting) const f = (a, b = 1) => a + b Flecha: no tiene this propio (...args) Parámetros rest Closure Función que recuerda las variables de donde se creó f.call(obj, a) · f.bind(obj) Fijar this IIFE (() => { … })() Ejecutar al momento con ámbito propio
Tema: Funciones, Objetos y Clases DOM const lista = document.querySelector("#lista"); document.querySelectorAll(".item").forEach(el => el.classList.toggle("activo")); const li = document.createElement("li"); li.textContent = texto; // seguro: no interpreta HTML li.dataset.id = 7; // data-id="7" lista.append(li); el.setAttribute("aria-expanded", "true"); el.closest("article"); el.remove(); Tema: DOM, Eventos y Formularios Eventos boton.addEventListener("click", e => { … }); lista.addEventListener("click", e => { // delegación const li = e.target.closest("li"); if (li) borrar(li.dataset.id); }); form.addEventListener("submit", e => { e.preventDefault(); const datos = Object.fromEntries(new FormData(form)); }); input.addEventListener("input", debounce(buscar, 300)); Otros: change, keydown (e.key), DOMContentLoaded, e.stopPropagation(). Fase de captura con { capture: true }.
Tema: DOM, Eventos y Formularios Formularios required · minlength · pattern · type="email" Validación nativa input.checkValidity() · validity.valueMissing Comprobar desde JS input.setCustomValidity("mensaje") Error propio ("" para quitarlo) form.reportValidity() Mostrar los mensajes novalidate Desactivar la validación del navegador
Tema: DOM, Eventos y Formularios fetch y async/await async function cargar(id) { const ctrl = new AbortController(); const t = setTimeout(() => ctrl.abort(), 5000); try { const res = await fetch(`/api/items/${id}`, { signal: ctrl.signal }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return await res.json(); } finally { clearTimeout(t); } } await fetch("/api/items", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(item) }); const [a, b] = await Promise.all([cargar(1), cargar(2)]); Tema: Asincronía, AJAX y Frameworks Bucle de eventos Pila de llamadas Código síncrono, de uno en uno Microtareas Promesas (then, await): antes que las macrotareas Macrotareas setTimeout, eventos, mensajes console.log(1); setTimeout(…2); Promise.resolve().then(…3); log(4) Imprime 1, 4, 3, 2
Tema: Asincronía, AJAX y Frameworks Almacenamiento y BOM localStorage.setItem(k, JSON.stringify(v)) Persistente, solo texto JSON.parse(localStorage.getItem(k) ?? "null") Leer sessionStorage Igual pero se borra al cerrar la pestaña location.href · history.pushState URL actual · cambiarla sin recargar new Date().toLocaleDateString("es-ES") Fecha en formato español Intl.NumberFormat("es-ES", {style:"currency", currency:"EUR"}) Moneda
Tema: Objetos Predefinidos y BOM