Chapter 2 of 14
Variables are named containers that store data. Understanding when to use let vs const is one of the first things to internalise.
// const — value cannot be reassigned (use this by default)
const name = "Nelson";
const pi = 3.14159;
// let — value can change (use when you know it will change)
let score = 0;
score = score + 10; // valid
score = 50; // valid
// var — the old way. Avoid it. Has confusing scoping behaviour.
var old = "don't use this";
// You cannot reassign a const
const age = 26;
age = 27; // TypeError: Assignment to constant variable// String — text
const firstName = "Nelson";
const message = 'Single quotes work too';
const greeting = `Template literal — embed: ${firstName}`; // backticks
// Number — integers AND decimals (one type for both)
const age = 26;
const price = 9.99;
const bigNum = 1_000_000; // underscore for readability
// Boolean
const isLoggedIn = true;
const isPremium = false;
// null — intentional absence of a value
const selectedCourse = null;
// undefined — a variable declared but not given a value
let username; // undefined
console.log(username); // undefined
// typeof — check what type a value is
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof null // "object" (a famous JS bug — null is not an object)
typeof undefined // "undefined"
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"TIP
Use const by default. Start every variable with const. If you get an error because you need to reassign it, change it to let. This practice reduces bugs by making you conscious of when values actually need to change.