What you'll learn
How to create a variable, give it a value, change it later, and show it with console.log.
Why it matters
Programs need to remember things: a score, a name, a price. A variable is how JavaScript remembers.
Explanation
A variable is a named box that holds a value. You create one with a keyword, a name, and = to put a value inside.
letmakes a variable you can change later.constmakes a variable that cannot be re-assigned.
Use const by default. Switch to let only when the value needs to change.
console.log(...) prints a value so you can see it. It is how you "look inside" while learning.
Example
const name = "Asha"; // a text value, cannot be re-assigned
let score = 10; // a number we will change
console.log(name); // prints: Asha
console.log(score); // prints: 10
score = score + 5; // change the value in the jar
console.log(score); // prints: 15
console.log("Hi " + name + ", your score is " + score);Step-by-step walkthrough
const name = "Asha"creates a jar callednameholding the textAsha.let score = 10creates a jar calledscoreholding10.- The first two
console.logcalls printAshaand10. score = score + 5reads the current value (10), adds 5, and puts 15 back in the jar. There is noletthe second time because the variable already exists.- The last line joins text and values with
+and printsHi Asha, your score is 15.
Try it yourself
Create a let variable called lives set to 3. Subtract 1 from it and print it.
VariablesJavaScript
Common mistakes
- Changing a
const.const x = 1; x = 2;throws a TypeError. Useletif it must change. - Using a variable before creating it, which throws a ReferenceError.
- Forgetting quotes around text.
const name = Ashalooks for a variable called Asha. - Typos in names.
scoreandScoreare different variables.
Quick quiz
Summary
- Variables store values:
letcan change,constcannot. - Use
constby default. console.logprints a value so you can see it.
Next: the kinds of values a variable can hold.