Null
Paulo7 de enero de 2026
Definición
Valor especial que indica la ausencia de un valor o la inexistencia de un objeto.
Descripción
Es común en muchos lenguajes para representar "sin datos". Diferente de undefined (no definido).
Ejemplo
TypeScript
// null vs undefined en JavaScript
let a; // undefined (no inicializada)
let b = null; // null (intencionalmente vacío)
// Verificar null/undefined
if (valor === null) { }
if (valor === undefined) { }
if (valor == null) { } // true para null Y undefined
// Nullish coalescing (??)
const nombre = usuario.nombre ?? 'Anónimo';
// Usa 'Anónimo' solo si nombre es null o undefined
// (no para '', 0, false como haría ||)
// Optional chaining (?.)
const ciudad = usuario?.direccion?.ciudad;
// Retorna undefined si algún nivel es null/undefined
// TypeScript - tipos nullable
function buscar(id: string): Usuario | null {
const usuario = db.find(id);
return usuario ?? null;
}
// Non-null assertion (cuidado!)
const elemento = document.getElementById('app')!;
// El ! dice "confía en mí, no es null"
// Evitar errores de null
// TypeError: Cannot read property 'x' of null
const valor = objeto?.propiedad ?? 'default';