Variables give names to values so your JavaScript can remember and reuse them. In this practical example, you will store a learner’s name, completed lessons, and weekly goal, then show a progress message on the page.
For the core concepts, read the JavaScript explanation on Playcode123.com. You can also copy examples from the JavaScript codes page and test small changes in the Sandbox.
let and const
Use const when the variable will not be assigned a different value. Use let when it needs to change later.
const learnerName = "Alex";
let completedLessons = 2;The variable names describe the data. Text is placed inside quotes; numbers are not.
Build a small progress tracker
Create an index.html file and paste in this complete example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Variables</title>
</head>
<body>
<h1>Weekly coding progress</h1>
<p id="progress"></p>
<script>
const learnerName = "Alex";
const weeklyGoal = 5;
let completedLessons = 2;
completedLessons = completedLessons + 1;
const message =
learnerName + " completed " + completedLessons +
" of " + weeklyGoal + " lessons.";
document.getElementById("progress").textContent = message;
</script>
</body>
</html>Expected result
The page should display: Alex completed 3 of 5 lessons. The starting value is 2, but the next line adds one before the message is created.
What happens step by step
learnerNamestores text.weeklyGoalstores a number that does not change.completedLessonsstarts at2.- The value is updated to
3. - The variables are combined into a message.
textContentplaces the message in the paragraph.
Common mistakes
- Changing a const: assigning a new value to a
constcauses an error. - Forgetting quotes: write
"Alex"for text. Without quotes, JavaScript looks for a variable namedAlex. - Using a variable before declaring it: declare the variable before the code that reads it.
- Inconsistent capitalization:
weeklyGoalandweeklygoalare different names. - Adding text instead of numbers:
"2" + 1produces"21", while2 + 1produces3. - Using unclear names: descriptive names make errors easier to find.
Exercise
Change the learner’s name and weekly goal. Start completedLessons at another number, add two completed lessons, and update the message so it also says how many lessons remain.
Check your work: open the browser console if no message appears. Look for spelling differences, missing quotes, or an attempt to change a const.