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 (forma tradicional)
Section titled “var (forma tradicional)”var nombre = "Juan";var edad = 25;let (ES6+)
Section titled “let (ES6+)”let nombre = "María";let edad = 30;const (para valores inmutables)
Section titled “const (para valores inmutables)”const PI = 3.14159;const URL_BASE = "https://api.ejemplo.com";Alcance (scope) y hoisting
Section titled “Alcance (scope) y hoisting”Scope de var
Section titled “Scope de var”- 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}Scope de let y const
Section titled “Scope de let y const”- Bloque-scoped
- No hoisted
function ejemplo() { let x = 1; if (true) { let x = 2; // Nueva variable console.log(x); // 2 } console.log(x); // 1}Hoisting
Section titled “Hoisting”El hoisting mueve las declaraciones al inicio:
console.log(x); // undefinedvar x = 5;
// Es equivalente a:var x;console.log(x);x = 5;
// Con let/const esto causa un error:console.log(y); // ReferenceErrorlet y = 5;Buenas prácticas al declarar
Section titled “Buenas prácticas al declarar”- Usar const por defecto
const CONFIG = { api: "https://api.ejemplo.com", timeout: 5000};- Usar let cuando necesites reasignar
let contador = 0;contador++;- Evitar var
// ❌ Malovar nombre = "Juan";
// ✅ Buenoconst nombre = "Juan";- Nombres descriptivos
// ❌ Maloconst x = 3600000;
// ✅ Buenoconst MILISEGUNDOS_POR_HORA = 3600000;- Declarar una variable por línea
// ❌ Malolet a = 1, b = 2, c = 3;
// ✅ Buenolet a = 1;let b = 2;let c = 3;Temporal Dead Zone (TDZ)
Section titled “Temporal Dead Zone (TDZ)”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";}Diferencias principales
Section titled “Diferencias principales”| Característica | var | let | const |
|---|---|---|---|
| Scope | Función | Bloque | Bloque |
| Hoisting | Sí | No | No |
| Redeclaración | Permitida | No permitida | No permitida |
| Reasignación | Permitida | Permitida | No permitida |
| TDZ | No | Sí | Sí |
Ejercicios prácticos
Section titled “Ejercicios prácticos”// 1. Corregir el siguiente códigovar 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 errorconst MAX_PUNTOS;MAX_PUNTOS = 100;
🐝