JavaScript Tutorial · JavaScript Basics · Lesson 5 of 44
JavaScript Variables
Declare variables with let and const — and why to avoid var.
let and const
Variables are named containers for values.
constdeclares a variable that cannot be reassigned. Use it by default.letdeclares a variable you will reassign later.
const name = "Ada";
let score = 10;
score = score + 5;
console.log(name, score);
Output
Ada 15
Trying to reassign a const throws TypeError: Assignment to constant variable.
const doesn't mean frozen
const protects the binding, not the value. An object or array declared with const can still be changed:
const user = { name: "Ada" };
user.name = "Grace"; // allowed: changing a property
const colors = ["red"];
colors.push("blue"); // allowed: changing the array
console.log(user, colors);
Output
{ name: 'Grace' } [ 'red', 'blue' ]What about var?
var is the old way to declare variables. It is function-scoped instead of block-scoped and is hoisted, which leads to confusing bugs. Modern code uses only let and const.
for (var i = 0; i < 3; i++) {}
console.log("var i after the loop:", i); // var leaks out of the block
for (let j = 0; j < 3; j++) {}
console.log(typeof j); // let stays inside the block
Output
var i after the loop: 3 undefined
Naming rules
- Use descriptive camelCase names:
userCount, notuc. - Constants that are truly fixed configuration are often written in UPPER_SNAKE_CASE:
const MAX_RETRIES = 3;
Test yourself
Which keyword should you use by default for variables that are never reassigned?
varletconststatic
Show answer
Answer: const