Chuleta de JavaScript

Variables, arrays, objetos, funciones flecha, métodos de array, el DOM y async/await en tablas para consultar rápido.

Referencia rápida. Para aprender cada tema a fondo, ve a los ejemplos interactivos de JavaScript.

Variables y tipos

let x = 5;           // reasignable
const nombre = "Ana"; // no reasignable (usa const por defecto)

// tipos: string, number, boolean, null, undefined, object, symbol, bigint
typeof x;            // "number"
`Hola ${nombre}`;    // template literal

Number("42");  String(42);  parseInt("42px");  Boolean(0);
x === y             // igualdad estricta (usa SIEMPRE ===)
a ?? b              // b si a es null/undefined
obj?.prop          // no peta si obj es null

Arrays

const xs = [1, 2, 3];
xs.push(4);  xs.pop();  xs.shift();  xs.unshift(0);
xs.length;   xs[0];     xs.at(-1);   xs.includes(2);
xs.slice(1, 3);         xs.indexOf(2);

xs.map(n => n * 2)                 // [2,4,6]
xs.filter(n => n % 2 === 0)        // [2]
xs.reduce((a, n) => a + n, 0)      // 6
xs.find(n => n > 1)                // 2
xs.forEach(n => console.log(n));
xs.sort((a, b) => a - b);
[...xs, 5]                         // spread

Objetos

const user = { nombre: "Ana", edad: 30 };
user.nombre;   user["edad"];
const { nombre, edad } = user;      // destructuring
const copia = { ...user, edad: 31 }; // spread + sobrescribir

Object.keys(user);    Object.values(user);   Object.entries(user);
"nombre" in user;     delete user.edad;

Funciones y control de flujo

function suma(a, b = 0) { return a + b; }
const doble = x => x * 2;
const saluda = (nombre) => `Hola ${nombre}`;

if (x > 0) { ... } else { ... }
for (const x of lista) { ... }
for (const k in objeto) { ... }
lista.forEach((x, i) => { ... });
switch (v) { case 1: ...; break; default: ... }
x ? "sí" : "no";

El DOM

document.querySelector(".clase");
document.querySelectorAll("li");        // NodeList
document.getElementById("id");

el.textContent = "hola";               // texto seguro
el.innerHTML = "<b>ojo con XSS</b>";
el.classList.add("activo");  el.classList.toggle("x");
el.setAttribute("href", "...");  el.dataset.id;
el.addEventListener("click", (e) => { e.preventDefault(); });

const nuevo = document.createElement("li");
padre.appendChild(nuevo);  el.remove();

Asincronía

async function cargar() {
  const res = await fetch("https://api.ejemplo.com/datos");
  if (!res.ok) throw new Error("HTTP " + res.status);
  const datos = await res.json();
  return datos;
}

cargar()
  .then(datos => console.log(datos))
  .catch(err => console.error(err));

setTimeout(() => { ... }, 1000);
await Promise.all([p1, p2]);

Otras chuletas

Java · Python · SQL · Git