JavaScript Variables
Learn to declare variables using let, const, and var in JavaScript.
Variables are the building blocks of JavaScript applications. They store data that your program can use and manipulate. Modern JavaScript offers three ways to declare variables: let, const, and var, each with different behaviors and use cases. Understanding when to use each one is crucial for writing clean, bug-free code. This exercise teaches you the fundamentals of JavaScript variable declaration.
📚 Concepts & Theory
Variable Declaration:
const - For values that won't change:
const PI = 3.14159;
const API_URL = "https://api.example.com";
// PI = 3.14; // Error! Cannot reassign
let - For values that will change:
let score = 0;
score = 10; // OK!
let count = 1;
count++; // Now count is 2
var - Old style (avoid in modern code):
var name = "Alice"; // Function-scoped
// Has hoisting issues - prefer let/const
Best Practices:
- Use
constby default - Use
letwhen you need to reassign - Avoid
varin modern JavaScript
// camelCase for variables
let userName = "John";
let totalPrice = 99.99;
// UPPER_SNAKE_CASE for constants
const MAX_SIZE = 100;
const API_KEY = "abc123";
🎯 Your Challenge
Declare a constant called `SITE_NAME` with the value "CodeStarter". Then declare a variable with `let` called `visitorCount` and set it to 0. Finally, increase `visitorCount` by 1.
📝 Starter Code
// Declare a constant for site name
// Declare a variable for visitor count
// Increase visitor count by 1
- Use const for values that never change
- Use let for values that will change
- UPPER_SNAKE_CASE is convention for constants
- ++ adds 1 to a variable
Solution
const SITE_NAME = "CodeStarter";
let visitorCount = 0;
visitorCount++;
Explanation
We use const for SITE_NAME because it should never change. We use let for visitorCount because it will be updated. The ++ operator is shorthand for adding 1 to a variable (equivalent to visitorCount = visitorCount + 1).
⚠️ Common Mistakes to Avoid
- Using var instead of let/const
- Trying to reassign a const
- Forgetting to use camelCase
- Not initializing variables before use