The basics of syntax

INPUT · Slides

Writing an update the short way

01 / 07

Writing the same name twice is a chore

Writing total = total + 300 means typing the same name twice every time you update. It is work, and it reads badly.

So there is a shorter way to write it.

02 / 07

Add and put it back with +=

total += 300 means exactly the same as total = total + 300.

-=, *= and /= work the same way.

let total = 0;total += 300;total += 450;console.log(total);

Result

750

03 / 07

Subtract, multiply and divide too

Change the symbol and the shape stays the same.

  • n -= 3n = n - 3
  • n *= 2n = n * 2
  • n /= 4n = n / 4
let n = 20;n -= 5;n *= 3;console.log(n);

Result

45

04 / 07

For one at a time, ++ and --

If you are only adding 1, there is something shorter still: n++. To take 1 off, n--.

It turns up any time something is counted one at a time, so make sure you recognise it.

let count = 0;count++;count++;console.log(count);

Result

2

05 / 07

+= works on strings as well

+= is not only for numbers. Use it on a string and it joins the new bit onto the end.

Same as + changing its job between numbers and strings.

let message = "hello";message += ", Yui";console.log(message);

Result

hello, Yui

06 / 07

Why write it short

Writing less means more than saving keystrokes.

In total = total + 300 the name appears twice, and that is room to get it wrong. Typing a different name on one side really does happen.

With total += 300 the name appears once. There is nothing left to get wrong. Shorter is usually safer as well.

07 / 07

Where this turns up next

+= and ++ are what you see most often inside a loop.

"Walk the array and add each one to the total." "Count how many were found." From the next chapter on, this shape is everywhere.

Get it into your fingers now and that chapter gets easier.

let sum = 0;sum += 10;sum += 20;sum += 30;console.log(sum);

Result

60