Values and variables
You'll learn to store values in variables with const and let, and to say what a variable holds.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want your program to remember things: a name, a balance, a score. To do that, you give each piece of data a name.
A piece of data is called a value: "Nusrat", 500, true. A name that holds a value is called a
variable. Think of your bKash app. The balance shown on screen is the value. "Balance" is the label
that always points to it, even when the amount changes.
const name = "Nusrat";let balance = 500;balance = balance - 120;console.log(balance); // 380
const makes a variable you will not point to a new value. let makes one you can change later.
Use const by default, and switch to let only when the value must change. Then, when you read
const, you know at a glance that it stays the same. You will also see var in old code. It is the old
way to write let; don't use it in new code.
The = sign does not mean "equal" here. It means "put the value on the right into the name on the left".
So balance = balance - 120 reads: take the balance, subtract 120, store the result back in balance.
Values come in kinds, called types. Text in quotes is a string, 500 is a number, and true
or false is a boolean. typeof tells you the type: typeof 500 is "number".
People often write const and then try to change it. JavaScript stops with
TypeError: Assignment to constant variable. That is not a disaster: it means the value really needs
let.
Good names help too. balance is better than b, and studentCount is better than x. Names can't
have spaces, so join words like studentCount.
When you read code, find each variable and ask two questions: what does it hold now, and can it change?
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1let score = 10;2score = score + 5;3const bonus = 2;4console.log(score * bonus);
balance should end at 350. Fix the code so both checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3After
let score = 10; score = score + 5;, what isscore? - 2 / 3What happens with
const city = "Dhaka"; city = "Sylhet";? - 3 / 3What is
typeof "500"?