Variables: let, const & var
A variable is a named reference to a value, such as a username, a price or a score. Modern JavaScript gives you two keywords for creating variables, let and const, plus the older var. Choosing the right one makes your code safer and easier to read.
Declaring variables with let and const
You declare a variable with a keyword and a name, and usually give it a starting value with =:
let score = 10; score = 15; // let can be reassigned console.log(score); const county = "Kisumu"; console.log(county); county = "Nakuru"; // const cannot
Use let for values that will change, such as a counter or a running total. Use const for values that should stay bound to the same thing, which in practice is most of them. A const must be given a value when it is declared: const rate; on its own is a SyntaxError. A let declared without a value starts as undefined.
let label can be moved to a new value; a const label stays attached to its first value.const stops reassignment, not change. If a const holds an object or array, you can still change what is inside it: const cart = []; cart.push("sugar"); is perfectly legal. What you can't do is make cart point at a different array. See Objects and Arrays.
The old keyword: var
Before 2015, var was the only option, and you will still see it in older tutorials and code. It behaves differently in ways that cause bugs:
varis function-scoped, not block-scoped, so it leaks out ofifblocks and loops.- The same
varcan be declared twice without any error, silently overwriting the first. - A
varcan be used before its declaration line and givesundefinedinstead of an error.
if (true) {
var oldStyle = "I leak out";
let modern = "I stay inside";
}
console.log(oldStyle);
console.log(modern);
Variables made with let and const live only inside the nearest pair of curly braces, which is almost always what you want. You will explore this on Scope & Closures. For new code, don't use var.
Hoisting and the temporal dead zone
Before running your code, the engine scans each scope and registers every declaration. This is called hoisting. The keywords differ in what happens if you use a variable before its line:
console.log(a); var a = 5; console.log(b); let b = 5;
A var is hoisted and set to undefined, so the first log quietly prints undefined, which hides the mistake. A let or const is also hoisted, but it stays uninitialised until its declaration line runs. The stretch of code between the start of the block and that line is called the temporal dead zone (TDZ), and touching the variable there throws an error. That error is helpful: it points you straight at the bug.
Naming rules and style
- Names may contain letters, digits, underscores
_and dollar signs$, but can't start with a digit:item2is fine,2itemis not. - Names are case-sensitive:
total,TotalandTOTALare different variables. - Reserved words such as
let,const,if,function,returnandclasscan't be names. - JavaScript convention is camelCase:
monthlyRent,isLoggedIn,mpesaBalance. Fixed settings known before the program runs are often written in capitals, such asVAT_RATE.
Choose names that explain the value. daysUntilExam is far better than d or x.
const name = "Baraka"; let points = 0; points = points + 5; // answered a question points += 3; // shorthand for points = points + 3 console.log(name, "has", points, "points");
Which keyword should I use?
A simple rule that professional teams follow: use const by default. Switch to let only when you know the variable must be reassigned, such as a loop counter or a total that grows. Avoid var. Code written this way tells the reader at a glance which values change, and the engine catches accidental reassignments for you.
Key points
letcreates a variable you can reassign;constcreates one you can't.constobjects and arrays can still have their contents changed.varis function-scoped, can be redeclared and givesundefinedbefore its line, so avoid it.- Using a
let/constvariable before its declaration throws an error (the temporal dead zone). - Use descriptive camelCase names, and prefer
constunless the value must change.
Tip: use the ← and → keys to move between pages.
