let, const and var
A variable stores a value under a name. Modern JavaScript has two keywords for creating them: const and let.
const: a value that won't be reassigned
JavaScript
const siteName = "CodeMIRAI";
const launchYear = 2026;
console.log(siteName, launchYear);Trying to reassign a const is an error:
JavaScript
const pi = 3.14159;
pi = 3;let: a value that will change
JavaScript
let score = 0;
score = score + 10;
score += 5;
console.log(score);Rule of thumb: use const by default, and let only when you know the value will change. It makes your intentions clear and prevents accidental changes.
const doesn't freeze objects
const stops you from pointing the name at a different value, but the contents of an object or array can still change:
JavaScript
const cart = ["apple"];
cart.push("pear"); // allowed: same array, new contents
console.log(cart);What about var?
Older code uses var. It has confusing rules (it ignores block scope and can be used before it's declared), so modern code uses let and const instead.
JavaScript
if (true) {
var leaky = "I escape the block!";
let safe = "I stay inside";
}
console.log(leaky);
console.log(typeof safe); // "undefined": safe doesn't exist hereNaming
- Names can contain letters, digits,
_and$, but cannot start with a digit. - They are case-sensitive.
- The convention is camelCase:
firstName,totalPrice,isLoggedIn.
JavaScript
const firstName = "Mei";
let itemsInCart = 3;
const isMember = true;
console.log(`${firstName} has ${itemsInCart} items. Member: ${isMember}`);Those backticks create a template literal, which you'll meet properly in the strings lesson.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.