Skip to content

Variables y constantes

Variables y constantes Fundamental

Section titled “Variables y constantes ”

Declaración con var, let y const Importante

Section titled “Declaración con var, let y const ”

JavaScript ofrece tres formas de declarar variables:

var nombre = "Juan";
var edad = 25;
let nombre = "María";
let edad = 30;
const PI = 3.14159;
const URL_BASE = "https://api.ejemplo.com";
  • Función-scoped
  • Hoisted al inicio de su contexto
function ejemplo() {
var x = 1;
if (true) {
var x = 2; // Misma variable
console.log(x); // 2
}
console.log(x); // 2
}
  • Bloque-scoped
  • No hoisted
function ejemplo() {
let x = 1;
if (true) {
let x = 2; // Nueva variable
console.log(x); // 2
}
console.log(x); // 1
}

El hoisting mueve las declaraciones al inicio:

console.log(x); // undefined
var x = 5;
// Es equivalente a:
var x;
console.log(x);
x = 5;
// Con let/const esto causa un error:
console.log(y); // ReferenceError
let y = 5;
  1. Usar const por defecto
const CONFIG = {
api: "https://api.ejemplo.com",
timeout: 5000
};
  1. Usar let cuando necesites reasignar
let contador = 0;
contador++;
  1. Evitar var
// ❌ Malo
var nombre = "Juan";
// ✅ Bueno
const nombre = "Juan";
  1. Nombres descriptivos
// ❌ Malo
const x = 3600000;
// ✅ Bueno
const MILISEGUNDOS_POR_HORA = 3600000;
  1. Declarar una variable por línea
// ❌ Malo
let a = 1, b = 2, c = 3;
// ✅ Bueno
let a = 1;
let b = 2;
let c = 3;

La TDZ es el período entre el inicio del scope y la declaración de la variable:

{
// TDZ para la variable nombre
console.log(nombre); // ReferenceError
let nombre = "Juan";
}
Característicavarletconst
ScopeFunciónBloqueBloque
HoistingNoNo
RedeclaraciónPermitidaNo permitidaNo permitida
ReasignaciónPermitidaPermitidaNo permitida
TDZNo
// 1. Corregir el siguiente código
var precio = 100;
var precio = 200; // ¿Qué problema hay aquí?
// 2. ¿Qué imprimirá?
const obj = { x: 1 };
obj.x = 2;
console.log(obj.x);
// 3. Identificar el error
const MAX_PUNTOS;
MAX_PUNTOS = 100;
🐝