Variables are containers that store data values. They're the fundamental building blocks of programming—you'll use them in every program you write. JavaScript gives you three ways to declare variables: var, let, and const. Let's master all three!
What Are Variables?
Think of a variable as a labeled box where you can store a value. You give the box a name, put something in it, and then you can use that name to retrieve or change what's inside.
// Creating a variable is like labeling a box
let userName = "John";
// The box (userName) now contains "John"
// You can look inside the box anytime
console.log(userName); // Output: John
// You can change what's in the box
userName = "Jane";
console.log(userName); // Output: JaneWhy Use Variables?
- Store data: Keep values for later use
- Reuse values: Use the same value multiple times
- Make code readable: Names explain what data means
- Enable calculations: Perform operations on stored values
- Track changes: Update values as your program runs
Declaring Variables
In JavaScript, you declare (create) a variable using one of three keywords: let, const, or var.
The Modern Way: let and const
Modern JavaScript (ES6+) uses let and const. These are what you should use in all new code.
// Using let - for values that can change
let age = 25;
let city = "New York";
// Using const - for values that won't change
const PI = 3.14159;
const birthYear = 1995;The Old Way: var
var is the original way to declare variables in JavaScript. While it still works, it has quirks that can cause bugs, so we use let and const instead.
// Old way - don't use this in new code
var oldVariable = "This is outdated";
// Modern way - use this instead
let newVariable = "This is better";Best Practice: Always use const by default. Only use let when you know you'll need to reassign the variable. Never use var in new code.
Understanding 'let'
let declares a variable that can be reassigned. Use it when you know the value will change.
Basic let Usage
// Declare and initialize
let score = 0;
console.log(score); // 0
// Reassign (change the value)
score = 10;
console.log(score); // 10
// Reassign again
score = score + 5;
console.log(score); // 15Declaring Without Initializing
// Declare without a value
let message;
console.log(message); // undefined
// Assign later
message = "Hello!";
console.log(message); // Hello!let Prevents Redeclaration
let userName = "John";
// This will cause an error!
let userName = "Jane"; // ❌ SyntaxError: Identifier 'userName' has already been declared
// Instead, just reassign:
userName = "Jane"; // ✅ This works!Practice with 'let'
Experiment with declaring and reassigning variables
console.log() to see your output in the console above.Understanding 'const'
const declares a constant—a variable that cannot be reassigned. Use it for values that should never change.
Basic const Usage
// Must initialize when declaring
const PI = 3.14159;
const MAX_USERS = 100;
const API_KEY = "abc123xyz";
console.log(PI); // 3.14159const Cannot Be Reassigned
const birthYear = 1990;
// This will cause an error!
birthYear = 1995; // ❌ TypeError: Assignment to constant variable
// const also can't be declared without a value
const age; // ❌ SyntaxError: Missing initializer in const declarationWhen to Use const
- Mathematical constants (PI, e, etc.)
- Configuration values that don't change
- Values you want to protect from accidental changes
- As your default choice (promotes safer, more predictable code)
// Good uses of const
const DAYS_IN_WEEK = 7;
const COMPANY_NAME = "Falytom";
const MAX_LOGIN_ATTEMPTS = 3;
// Use const for values that won't change
const firstName = "John";
const birthDate = "1990-05-15";
// Even if you perform calculations
const currentYear = 2024;
const birthYear = 1995;
const age = currentYear - birthYear; // const because we won't change itImportant Note About Objects and Arrays:
With const, you can't reassign the variable, but you can modify the contents of objects and arrays. We'll cover this in detail in later lessons.
// This is allowed:
const colors = ["red", "blue"];
colors.push("green"); // ✅ Modifying array contents is OK
console.log(colors); // ["red", "blue", "green"]
// This is NOT allowed:
colors = ["yellow"]; // ❌ Cannot reassign the variablePractice with 'const'
Work with constants that can't be reassigned
console.log() to see your output in the console above.Understanding 'var' (The Old Way)
var was the only way to declare variables before ES6 (2015). While it still works, it has confusing behaviors that make bugs more likely.
Problems with var
1. var Can Be Redeclared
var age = 25;
console.log(age); // 25
// You can redeclare (this is confusing!)
var age = 30;
console.log(age); // 30
// With let, this would be an error (which is good!)
let score = 10;
let score = 20; // ❌ Error: already declared2. var Has Function Scope (Not Block Scope)
// var ignores block scope
if (true) {
var x = 10;
}
console.log(x); // 10 - accessible outside the block!
// let respects block scope
if (true) {
let y = 10;
}
console.log(y); // ❌ Error: y is not defined3. var Is Hoisted
// This doesn't error, but prints undefined
console.log(name); // undefined (not an error!)
var name = "John";
// With let, this would error (which is better!)
console.log(age); // ❌ Error: Cannot access 'age' before initialization
let age = 25;Don't Use var: Always use let or const in modern JavaScript. The only reason to know about var is so you can understand older code you might see.
See why let is better than var
var (Old & Problematic)
// Old way with var
var userName = "John";
var userAge = 25;
// Can redeclare (bad!)
var userName = "Jane";
// Leaks out of blocks
if (true) {
var temp = "test";
}
console.log(temp); // Works (bad!)let (Modern & Safe)
// Modern way with let/const
let userName = "John";
let userAge = 25;
// Cannot redeclare (good!)
// let userName = "Jane"; // Error
// Respects block scope
if (true) {
let temp = "test";
}
// console.log(temp); // Error (good!)Variable Naming Rules and Conventions
Rules You MUST Follow
Breaking these will cause errors:
- Must start with a letter, underscore (_), or dollar sign ($)
- Can contain letters, digits, underscores, and dollar signs
- Cannot use reserved words (let, if, for, class, etc.)
- Are case-sensitive (age and Age are different)
- Cannot contain spaces or hyphens
// Valid variable names
let userName = "John";
let user_name = "John";
let _privateName = "John";
let $price = 99.99;
let age2 = 25;
// Invalid variable names (will error)
let 2users = 10; // ❌ Can't start with number
let user-name = "John"; // ❌ Can't use hyphens
let user name = "John"; // ❌ Can't have spaces
let let = "test"; // ❌ Can't use reserved wordsBest Practices (Conventions)
Follow these for clean, professional code:
- Use camelCase for regular variables (firstName, userAge)
- Use UPPERCASE for constants (PI, MAX_VALUE)
- Use descriptive names (age, not a)
- Start with lowercase letter
- Avoid single letters except in loops (i, j, k)
- Use English words (not abbreviations or different languages)
// Good variable names (descriptive and clear)
let firstName = "John";
let lastName = "Doe";
let userAge = 25;
let isLoggedIn = true;
let totalPrice = 99.99;
let maxAttempts = 3;
// Poor variable names (too short or unclear)
let fn = "John"; // What does 'fn' mean?
let x = 25; // What is 'x'?
let data = true; // What kind of data?
let t = 99.99; // What is 't'?
// Constants (uppercase)
const PI = 3.14159;
const MAX_USERS = 100;
const API_ENDPOINT = "https://api.example.com";Case Sensitivity
// JavaScript is case-sensitive - these are all different variables
let name = "John";
let Name = "Jane";
let NAME = "Bob";
let nAmE = "Alice";
console.log(name); // John
console.log(Name); // Jane
console.log(NAME); // Bob
console.log(nAmE); // Alice✍️ Naming Convention:
Always stick to camelCase for regular variables: first word lowercase, subsequent words capitalized. This is the JavaScript standard: userName, totalPrice, isActive.
Introduction to Scope
Scope determines where a variable can be accessed in your code. Understanding scope is crucial for writing bug-free code.
Block Scope (let and const)
// Variables declared with let/const are block-scoped
{
let blockVariable = "I'm in a block";
console.log(blockVariable); // ✅ Works
}
console.log(blockVariable); // ❌ Error: not defined
// Common with if statements
if (true) {
let message = "Hello";
console.log(message); // ✅ Works inside block
}
console.log(message); // ❌ Error: not accessible outsideFunction Scope
function greet() {
let name = "John";
console.log(name); // ✅ Works inside function
}
greet();
console.log(name); // ❌ Error: not defined outside functionGlobal Scope
// Variable declared outside any block or function
let globalVariable = "I'm global";
function test() {
console.log(globalVariable); // ✅ Accessible everywhere
}
test();
console.log(globalVariable); // ✅ Also works hereVariable Scope Visualization
See how scope affects variable accessibility
globalVar="accessible everywhere"functionVar="only in function"globalVar="accessible everywhere"blockVar="only in block"functionVar="only in function"globalVar="accessible everywhere"Remember: Variables declared inside a block or function are only accessible within that block or function. Variables declared outside are accessible everywhere.
Choosing Between let and const
Use const When:
- The value won't be reassigned
- You want to prevent accidental changes
- Declaring constants (PI, MAX_VALUE, etc.)
- You're not sure (const is the safer default)
Use let When:
- The value will change (counters, accumulators)
- You're reassigning in a loop
- The variable's value is calculated over time
// Use const for values that don't change
const userName = "John";
const birthYear = 1990;
const PI = 3.14159;
// Use let for values that will change
let count = 0;
count = count + 1;
count = count + 1;
let score = 0;
score = score + 10;
let temperature = 72;
temperature = temperature + 5;
// Start with const, change to let if needed
const maxAttempts = 3; // Won't change
let currentAttempt = 0; // Will increment🎯 Pro Tip:
Always start with const. If you later realize you need to reassign the variable, change it to let. This makes your code safer and more predictable.
Common Mistakes with Variables
1. Forgetting to Declare Variables
// Without strict mode, this creates a global variable (bad!)
userName = "John"; // ❌ No let/const/var
// Always declare your variables
let userName = "John"; // ✅ Correct2. Trying to Reassign const
const age = 25;
age = 26; // ❌ TypeError: Assignment to constant variable
// Use let if you need to reassign
let age = 25;
age = 26; // ✅ Works3. Using Variables Before Declaration
console.log(name); // ❌ Error with let/const
let name = "John";
// Always declare before using
let name = "John";
console.log(name); // ✅ Works4. Confusing Variable Scope
if (true) {
let message = "Hello";
}
console.log(message); // ❌ Error: message not defined
// Fix: Declare outside if needed elsewhere
let message;
if (true) {
message = "Hello";
}
console.log(message); // ✅ WorksPractical Examples
Example 1: User Profile
// User data that won't change
const userId = "user123";
const accountCreated = "2024-01-15";
// User data that might change
let userName = "John Doe";
let email = "john@example.com";
let isVerified = false;
console.log(`User: ${userName}`);
console.log(`Email: ${email}`);
console.log(`Verified: ${isVerified}`);
// Update changeable data
userName = "John Smith";
isVerified = true;
console.log(`Updated user: ${userName}`);
console.log(`Now verified: ${isVerified}`);Example 2: Shopping Cart
// Constants
const TAX_RATE = 0.08;
const SHIPPING_COST = 5.99;
// Variables that change
let itemPrice = 29.99;
let quantity = 2;
// Calculate totals
let subtotal = itemPrice * quantity;
let tax = subtotal * TAX_RATE;
let total = subtotal + tax + SHIPPING_COST;
console.log(`Subtotal: $${subtotal}`);
console.log(`Tax: $${tax.toFixed(2)}`);
console.log(`Shipping: $${SHIPPING_COST}`);
console.log(`Total: $${total.toFixed(2)}`);Shopping Calculator
Practice with const and let in a real scenario
console.log() to see your output in the console above.Key Takeaways
- Variables store data values that can be used throughout your code
- Use
constfor values that won't be reassigned (default choice) - Use
letfor values that will change - Never use
varin modern JavaScript constmust be initialized when declaredletandconstare block-scoped- Variable names should be descriptive and use camelCase
- Variables are case-sensitive
- Always declare variables before using them
- Scope determines where a variable can be accessed
What's Next?
You now understand how to create and use variables in JavaScript! Variables are the foundation—you'll use them in every single program you write from now on.
In the next lesson, we'll explore Data Types—the different kinds of values you can store in variables. You'll learn about numbers, strings, booleans, and more, and how to check what type of data you're working with.
💪 Practice Challenge:
Before moving on, try this:
- Create variables for your name, age, city, and favorite hobby
- Use const for values that won't change, let for values that might
- Print a sentence using all your variables with template literals
- Create a simple calculator that stores two numbers and calculates their sum, difference, product, and quotient
Test Your Understanding
Which keyword should you use for a value that won't change?
// Store PI value
____ pi = 3.14159;