Assignment Shortcuts

Grade 3, page 3 of 11. A one-minute read.

In Grade 1, you learned to update a variable using its own value, like score = score + 10. This is so common that JavaScript has shortcuts for it:

ShortcutSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 5x = x * 5
x /= 5x = x / 5
x %= 5x = x % 5
x **= 2x = x ** 2
JavaScript
let coins = 100;

coins += 50;
console.log(coins);

coins -= 30;
console.log(coins);

coins *= 2;
console.log(coins);

coins /= 4;
console.log(coins);

It prints

150
120
240
60

The += shortcut works on strings too, which is great for building up a message bit by bit:

JavaScript
let shoppingList = "Shopping list:";
shoppingList += " plantain,";
shoppingList += " eggs,";
shoppingList += " bread";
console.log(shoppingList);

It prints

Shopping list: plantain, eggs, bread

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning