Variables
Store values with const and let, then update them as needed.
Quick Summary
Variables are named containers for data. In JavaScript, use const for values that should not be reassigned and let for values that will change. Initialize variables when you declare them to avoid undefined, and choose clear, descriptive names so your code reads like a sentence. Most of the time, use const by default and switch to let only when reassignment is required.
Understanding Variables
Think of a variable as a labeled box that holds information. The label (variable name) helps you find and use the information later.
Declaring Variables
JavaScript offers three ways to declare variables:
const - For values that won't change (immutable binding):
const PI = 3.14159;
const apiUrl = "https://api.example.com";
const maxRetries = 3;
let - For values that will change:
let score = 0;
let currentUser = null;
let isLoading = true;
var - The old way (avoid in modern code):
var oldStyleVariable = "not recommended";
Naming Conventions
Good variable names make code self-documenting:
| Bad | Good | Why |
|-----|------|-----|
| x | userAge | Descriptive |
| data | productList | Specific |
| temp | previousValue | Meaningful |
| flag | isAuthenticated | Clear intent |
camelCase Convention
JavaScript uses camelCase for variable names:
- First word lowercase, subsequent words capitalized
firstName,totalAmount,isUserLoggedIn
const vs let Decision Tree
-
Will this value ever need to change?
- No → Use
const - Yes → Use
let
- No → Use
-
Default to
const— it prevents accidental reassignment and signals intent
Try It Yourself
Here's a practical example you can try. Copy this code and run it in your browser's console (press F12 to open developer tools) or in the Code Playground.
// Use const for values that won't change
const appName = "TaskManager";
const maxFileSize = 5 * 1024 * 1024; // 5MB in bytes
// Use let for values that will change
let currentStep = 1;
let userInput = "";
let isFormValid = false;
// Variables can be reassigned with let
currentStep = 2;
isFormValid = true;
// But const prevents reassignment
// appName = "NewName"; // Error!
// Initialize with meaningful defaults
let items = [];
let errorMessage = null;
let retryCount = 0;Key Takeaways
- ✓Store values with const and let, then update them as needed.
- ✓Practice with real code examples to solidify your understanding
- ✓This concept builds the foundation for more advanced topics
Related Learning Resources
Continue your programming journey with these related tutorials: