01 / 06
What is painful about typing values in
The basics of syntax
INPUT · Slides
01 / 06
Type the same value in over and over and, when you want to change it, you have to hunt down every one of them. Miss one and you have a bug.
With a variable there is only ever one place to edit.
let price = 300;console.log(price * 2);console.log(price * 5);Result
600 1500
02 / 06
console.log(300 * 8) tells you nothing about what is being worked out. price * count tells you just by being read.
You spend longer reading code than writing it. A name is a note to your future self.
let price = 300;let count = 8;console.log(price * count);Result
2400
03 / 06
It is not only values you typed that go into a variable. The result of a sum goes in just the same.
Name the halfway results and you can break a long sum into pieces.
let price = 300;let count = 8;let total = price * count;console.log(total);Result
2400
04 / 06
You can use what is in one variable to make another.
Breaking it small and stacking it up like this is how readable code gets written.
let price = 300;let count = 8;let total = price * count;let tax = total / 10;console.log(total + tax);Result
2640
05 / 06
A variable lets you keep the initial value in one place in the source.
Change let price = 300; below to let price = 400; and run the program again. The total becomes 3200 and the tax becomes 320. Running again recalculates each line in order.
let price = 300;let count = 8;let total = price * count;console.log(total);console.log(total / 10);Result
2400 240
06 / 06
A name should say what is inside.
a, x, data … no idea what is in thereprice, userName, total … you read it and you knowClear beats short. A longer name is fine, as long as you in three days can read it.
let a = 300;let price = 300;console.log(a * 8);console.log(price * 8);Result
2400 2400