Variables in JavaScript
A variable is a named box where you can store a value so you can use it later.
How to create a variable
Use const when the value should not change, and let when the value needs to change later.
Can edit
const name = "Alex";
let age = 30;
console.log(age);Example explained
Let's read the code line by line:
const name = "Alex";creates a variable namednameand stores the text"Alex"inside it. We useconstbecause this name is not meant to change in this example.let age = 30;creates a variable namedageand stores the number30inside it. We useletbecause age is a value that could change later.console.log(age);prints the current value ofagein the output section below the code.
Why it matters
Variables let you reuse values without typing them over and over. You can also update them as your program runs.
Mini Task
Edit the code block above and try this:
- Change
30to another age. - Click Run.
- Check how the output changes below the code.
Short Quiz
Question 1: Which keyword should you usually use when a value should not change?
A) const
B) let
C) console.log
Question 2: Which keyword should you use when a value needs to change later?
A) const
B) let
C) string
(Answers: 1 - A, 2 - B)
Challenge
Now try updating a variable more than once. Click Run and watch the final output.
Can edit
let score = 0;
score = score + 1;
score = score + 1;
score = score + 1;
console.log(score);Summary
- A variable stores a value under a name.
- Use
constby default. - Use
letwhen the value needs to change later. console.log()lets you check a variable's current value in the output section.