Lesson 1.1: Variables
Duration: 45 minutes
Learning Objectives
By the end of this lesson, you will be able to:
- Understand what variables are and why we need them
- Declare variables using
letandconst - Know the difference between
let,const, andvar - Follow naming conventions for variables
What is a Variable?
Think of a variable as a labeled box where you can store information. Just like you might have a box labeled "Photos" to store your pictures, in programming we use variables to store data with meaningful names.
let userName = 'Alice';
let age = 25;
let isStudent = true;
In this example:
userNameis a box containing the text "Alice"ageis a box containing the number 25isStudentis a box containing true (yes/no value)
Declaring Variables with let
Use let when you need a variable whose value might change later.
let score = 0;
console.log(score); // Output: 0
score = 10;
console.log(score); // Output: 10
score = score + 5;
console.log(score); // Output: 15
The let keyword tells JavaScript: "Create a new variable that I can update later."
Rules for let:
- You can change the value after declaration
- You cannot declare the same variable twice in the same scope
let message = "Hello";
message = "Hi"; // This is fine - updating the value
let message = "Hey"; // Error! Cannot declare 'message' again
Declaring Variables with const
Use const when you have a value that should never change.
const PI = 3.14159;
const MAX_USERS = 100;
const APP_NAME = 'My Application';
The const keyword tells JavaScript: "Create a variable that cannot be reassigned."
const birthYear = 1995;
birthYear = 1996; // Error! Cannot reassign a constant
When to Use const:
- Configuration values that stay the same
- Mathematical constants (like PI)
- References that should not change
Best Practice: Start with const by default. Only use let when you know the value needs to change.
Why Not var?
You might see var in older code:
var oldWay = 'This is the old way';
Avoid using var. Here is why:
Problem 1: var Ignores Block Scope
if (true) {
var leaked = 'I escaped!';
let contained = 'I stay here';
}
console.log(leaked); // Output: "I escaped!" - Unexpected!
console.log(contained); // Error! contained is not defined
Variables declared with var can "leak" outside of code blocks, causing unexpected behavior.
Problem 2: var Can Be Re-declared
var name = "Alice";
var name = "Bob"; // No error, but confusing!
let name = "Alice";
let name = "Bob"; // Error! This catches our mistake
With var, you can accidentally overwrite variables without knowing it.
Summary:
| Feature | let |
const |
var |
|---|---|---|---|
| Can reassign | Yes | No | Yes |
| Block scoped | Yes | Yes | No |
| Can re-declare | No | No | Yes |
| Recommended | Yes | Yes | No |
Naming Variables
Good variable names make code readable. Follow these conventions:
Use camelCase
// Good
let firstName = 'Alice';
let totalPrice = 99.99;
let isLoggedIn = true;
// Bad
let firstname = 'Alice'; // Hard to read
let TOTALPRICE = 99.99; // Looks like a constant
let is_logged_in = true; // Not JavaScript style
Use Descriptive Names
// Good - clear what the variable contains
let userAge = 25;
let productCount = 42;
let emailAddress = 'user@example.com';
// Bad - unclear meaning
let a = 25;
let x = 42;
let str = 'user@example.com';
Constants in UPPER_CASE
const MAX_RETRY_COUNT = 3;
const API_BASE_URL = 'https://api.example.com';
const DEFAULT_TIMEOUT = 5000;
Practical Examples
Example 1: User Profile
const userId = 'user_12345'; // Never changes
let userName = 'Alice'; // Can be updated
let loginCount = 0; // Will increase
// User logs in
loginCount = loginCount + 1;
console.log(userName + ' has logged in ' + loginCount + ' times');
Example 2: Shopping Cart
const TAX_RATE = 0.08; // Tax rate is fixed
let cartTotal = 0; // Will change as items added
// Add items
cartTotal = 29.99;
cartTotal = cartTotal + 15.99;
// Calculate final price
const finalPrice = cartTotal + cartTotal * TAX_RATE;
console.log('Total with tax: $' + finalPrice);
Example 3: Game Score
const POINTS_PER_COIN = 10;
const POINTS_PER_ENEMY = 50;
let playerScore = 0;
// Player collects coins
playerScore = playerScore + POINTS_PER_COIN;
playerScore = playerScore + POINTS_PER_COIN;
// Player defeats enemy
playerScore = playerScore + POINTS_PER_ENEMY;
console.log('Current score: ' + playerScore); // Output: 70
Exercises
Exercise 1: Variable Declaration
Create variables for a book:
- A constant for the ISBN (use "978-0-13-468599-1")
- A variable for the current page (start at 1)
- A variable for the bookmark status (start as false)
Solution
const ISBN = '978-0-13-468599-1';
let currentPage = 1;
let isBookmarked = false;
console.log('ISBN: ' + ISBN);
console.log('Page: ' + currentPage);
console.log('Bookmarked: ' + isBookmarked);
Exercise 2: Update Variables
Start with a temperature of 20 degrees. Update it to 25, then to 18.
Solution
let temperature = 20;
console.log('Temperature: ' + temperature); // 20
temperature = 25;
console.log('Temperature: ' + temperature); // 25
temperature = 18;
console.log('Temperature: ' + temperature); // 18
Exercise 3: Fix the Errors
Find and fix the errors in this code:
const userName = "Alice";
userName = "Bob";
let score = 100;
let score = 200;
var total = 50;
Solution
// Error 1: Cannot reassign const - use let instead
let userName = 'Alice';
userName = 'Bob';
// Error 2: Cannot redeclare let - just reassign
let score = 100;
score = 200;
// Error 3: var works but should be let
let total = 50;
Key Takeaways
- Variables store data with meaningful names
- Use
constfor values that never change (default choice) - Use
letfor values that will be updated - Avoid
var- it has confusing behavior - Name variables clearly using camelCase
- Constants use UPPER_CASE for easy identification
Resources
| Resource | Type | Description |
|---|---|---|
| MDN: let | Documentation | Official let reference |
| MDN: const | Documentation | Official const reference |
| JavaScript.info: Variables | Tutorial | Detailed variable tutorial |
Next Lesson
Now that you can store data in variables, let's learn about the different types of data you can store.