JavaScript Variables
A variable is a named container for a value. You create one, put data in it, and read the data back later. Nearly everything in JavaScript builds on variables, so getting the basics right early saves you from confusing bugs later.
Modern JavaScript gives you three keywords: let, const, and var. Use const for values that never change and let for values that do. var is the old keyword: it is function-scoped and hoisted, which means it is moved to the top of its function and can be read before it is written. That behavior causes bugs, so new code should use let and const instead.
let and const are block-scoped. A block is anything between two curly braces, like an if statement or a loop. A variable declared inside a block stays inside it. Variables also hold data types: strings for text, numbers for math, booleans for true or false, and undefined when nothing has been stored yet.
let versus const
The rule is simple: const for values that stay the same, let for values that change. A counter or a score needs let. A tax rate or a fixed limit works fine as const. If you try to reassign a const, JavaScript throws an error, which is usually a sign you picked the wrong keyword.
const taxRate = 0.08;
let total = 0;
total = total + 19.99; // let can change
Naming rules and habits
Names can contain letters, digits, underscores, and dollar signs, but cannot start with a digit. The community convention is camelCase: start lowercase, then capitalize each new word. Pick clear names like itemCount over short ones like x.
const itemCount = 3;
let cartTotal = 0;
const user2 = "Ada"; // digits are fine later in the name
Syntax
let count = 0;
const max = 10;
count = count + 1; // let can change, const cannot
0.1+0.2 !== 0.3 in JS
Numbers are binary floats — 0.1+0.2 is 0.30000000000000004. Never compare money with ===, round first.
Math.round((0.1+0.2)*100)/100 // 0.3
Good to know
- const means the value cannot be reassigned; let means it can.
- var is function-scoped and hoisted; let and const are block-scoped.
- Use camelCase names that say what the value holds.
- Strings, numbers, booleans, and undefined are the core data types.