Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Variables are labeled containers that store data in your program. Think of them like boxes with names on them - you can put things in, take things out, and change what's inside!
For values that can change
For values that stay the same
The old way (avoid it)
How to create variables with let and const
When you know the value will change later
let counter = 0; counter++; // Now 1 counter++; // Now 2 counter++; // Now 3 console.log(counter); // 3 // Perfect for counters, // loops, and changing values!
When the value won't change (most of the time!)
const name = 'Alice'; const age = 25; const isStudent = true; // These won't change! // Prevents accidental reassignment // Makes code more predictable ✅
Using let and const together
• Start with letter, _, or $
• Can contain letters, numbers, _, $
• Use camelCase convention
• Can't start with number
• No hyphens or spaces
• Can't use reserved words
Use descriptive, meaningful names
With const, you can't reassign the variable, but you CAN modify the contents of objects and arrays!
// With arrays
const colors = ['red', 'blue'];
colors.push('green'); // ✅ Works!
console.log(colors); // ['red', 'blue', 'green']
// colors = ['yellow']; // ❌ Error! Can't reassign
// With objects
const user = { name: 'Alice', age: 25 };
user.age = 26; // ✅ Works! Can modify
console.log(user.age); // 26
// user = { name: 'Bob' }; // ❌ Error! Can't reassignconst means the variable binding is constant, not the value itself. For objects and arrays, the reference stays the same, but you can change what's inside!if (true) {
var x = 5;
}
console.log(x); // 5 - leaks out! ❌
if (true) {
let y = 10;
}
console.log(y); // Error - stays inside! ✅console.log(a); // undefined (not error!) ❌ var a = 5; console.log(b); // Error! ✅ let b = 10;
var name = 'Alice'; var name = 'Bob'; // No error! ❌ let age = 25; let age = 30; // Error! ✅ Prevents bugs
const by default, and let when you need to reassign!const by defaultlet only when you need to reassignvar