Lección 2 · 2 de 20
let, const y tipos de datos · JavaScript
Guarde valores en variables con let y const, y descubra con typeof los tipos de datos de JavaScript: cadenas, números, booleanos, undefined y null.

Una variable es un nombre que guarda un valor. Con const se declara una que no cambiará, como shopName; con let, una que sí puede cambiar, como loavesLeft, que pasa de 40 a 28 cuando se le asigna loavesLeft - 12.
Use const siempre que pueda y let solo cuando el valor tenga que cambiar: así el código dice claramente qué es fijo. Si intenta dar otro valor a una const (quite las // de la última línea), JavaScript se detiene con un error.
El operador `typeof` dice de qué tipo es un valor. El texto es string; los números, enteros o con decimales, son number; true y false son boolean.
Una variable declarada sin valor, como nextDelivery, vale `undefined`. En cambio, `null` es un «vacío» que se pone a propósito; typeof null da object por un error histórico del lenguaje que ya no se puede corregir.
En JavaScript el tipo va con el valor, no con la variable: label empieza siendo un número y después guarda un texto. Es cómodo, pero conviene no mezclar tipos en la misma variable.
Código · main.js
// const: a value that will not change. let: a value that can change.const shopName = "Corner Bakery";let loavesLeft = 40;console.log(shopName, "opens with", loavesLeft, "loaves");loavesLeft = loavesLeft - 12; // let accepts a new valueconsole.log("After the morning rush:", loavesLeft);// typeof tells you the type of any value.const price = 1.25;const isOpen = true;let nextDelivery; // declared, but without a value yetconst closedDay = null;console.log(typeof shopName); // stringconsole.log(typeof price); // numberconsole.log(typeof isOpen); // booleanconsole.log(typeof nextDelivery, nextDelivery);console.log(typeof closedDay); // "object": an old quirk of the language// The type belongs to the value, not to the variable.let label = 42;console.log(typeof label);label = "forty-two";console.log(typeof label);// Giving a const a new value is an error (remove the // to see it):// shopName = "New Bakery";Salida · node main.js
Corner Bakery opens with 40 loaves After the morning rush: 28 string number boolean undefined undefined object number string
Para recordar
constpara valores fijos;letpara los que cambian.typeofdevuelve el tipo:string,number,boolean,undefined…undefinedes «sin valor todavía»;nulles «vacío a propósito».- Dar otro valor a una
constes un error.
Ejercicio
Añada una constante bakerName con un nombre y una variable isHoliday con false; escriba su tipo con typeof y después cambie isHoliday a true.