The basics of syntax

INPUT · Slides

Why bother with variables

01 / 06

What is painful about typing values in

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

The name does the explaining

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

A worked-out result can have a name too

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

Build variables out of variables

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

One place to edit

The best thing about a variable is that when you change the value, everything follows.

Change price to 400 below and the total and the tax are both worked out again. Typed in by hand, that would be three edits.

let price = 300;let count = 8;let total = price * count;console.log(total);console.log(total / 10);

Result

2400
240

06 / 06

How to name things

A name should say what is inside.

  • a, x, data … no idea what is in there
  • price, userName, total … you read it and you know

Clear 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