Declaring Variables
Variables are containers for storing data values. Think of them as labeled boxes where you can put information and retrieve it later.
JavaScript provides three keywords for declaring variables:
let - The modern way to declare variables that can change
- Block-scoped (only accessible within their code block)
- Can be reassigned but not redeclared in the same scope
const - For values that should not be reassigned
- Block-scoped like let
- Must be initialized when declared
- Cannot be reassigned (but objects/arrays can be modified)
var - The legacy way (avoid in modern code)
- Function-scoped (not block-scoped)
- Can be redeclared and reassigned
- Has "hoisting" quirks that can cause bugs
Naming Conventions:
- Use camelCase for variables: myVariableName
- Use UPPER_SNAKE_CASE for constants: MAX_VALUE
- Be descriptive: userEmail instead of e
- Start with a letter, underscore, or dollar sign
Code Examples
// let - for values that will change
let score = 0;
console.log("Initial score:", score);
score = 10; // Reassignment is OK
console.log("Updated score:", score);
// const - for values that shouldn't change
const PI = 3.14159;
const MAX_USERS = 100;
console.log("PI:", PI);
// const with objects - contents CAN change
const user = { name: "Alice", age: 25 };
user.age = 26; // This is allowed!
console.log("User:", user);
// But reassigning the whole object fails
// user = { name: "Bob" }; // Error!Use const by default, and only use let when you know the value needs to change. This makes your code more predictable.
// Block scope demonstration
let globalVar = "I'm global";
if (true) {
let blockVar = "I'm in a block";
console.log(globalVar); // Works - global is accessible
console.log(blockVar); // Works - we're inside the block
}
console.log(globalVar); // Works
// console.log(blockVar); // Error! blockVar doesn't exist here
// Function scope
function myFunction() {
let functionVar = "I'm in a function";
console.log(functionVar); // Works
}
myFunction();
// console.log(functionVar); // Error! functionVar doesn't exist hereScope determines where variables are accessible. Block-scoped variables (let/const) are only available within their curly braces.
Quick Quiz
1. Which keyword should you use for a value that won't change?
2. What happens if you try to use a let variable outside its block?
3. Can you modify properties of a const object?
Was this lesson helpful?