Start learning free

LESSON 27 OF 348 · CALCULATIONS WITH NUMBERS

Augmented Assignment Operators in TypeScript: +=, -=, *= and More

Lesson Read the full explanation

In programming, it is common to use assignments to modify the contents of a variable.

Remember that everything to the right of the equals sign (=) is evaluated first, so we can say:

myVar = myVar + 5;

to add 5 to myVar.

Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.

One such operator is the += operator:

let myVar = 10;
myVar += 5;
console.log(myVar);

This code would print 15 to the console. We call myVar += 5 an augmented assignment.

There is one such operator for every other arithmetic operator we've learned:

For subtraction: -=

let myVar = 10;
myVar -= 5; // short for myVar = myVar - 5;
console.log(myVar); // Prints 5

For multiplication: *=

let myVar = 3;
myVar *= 5; // short for myVar = myVar * 5;
console.log(myVar); // Prints 15

For division: /=

let myVar = 20;
myVar /= 4; // short for myVar = myVar / 4;
console.log(myVar); // Prints 5

For remainder: %=

let myVar = 11;
myVar %= 3; // short for myVar = myVar % 3;
console.log(myVar); // Prints 2

For exponentiation: **=

let myVar = 3;
myVar **= 3; // short for myVar = myVar ** 3;
console.log(myVar); // Prints 27

Assignment
Follow the Coding Tutorial and let's do some augmented assignments.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 7
    Ctrl + Enter to check

    TYPESCRIPT · CALCULATIONS WITH NUMBERS

    Augmented Assignment Operators in TypeScript, explained

    What an augmented assignment is

    Changing a variable based on its own value is a very common step. Since the right side of = is evaluated first, this line adds 5 to myVar:

    myVar = myVar + 5;
    

    An augmented assignment (also called a compound assignment) does the arithmetic and the assignment in one operator, so the variable name is written only once:

    let myVar = 10;
    myVar += 5;
    console.log(myVar); // 15
    

    There is one such operator for each arithmetic operator:

    OperatorMeaningExampleResult
    +=x = x + y10 then x += 515
    -=x = x - y10 then x -= 55
    *=x = x * y3 then x *= 515
    /=x = x / y20 then x /= 45
    %=x = x % y11 then x %= 32
    **=x = x ** y3 then x **= 327

    The variable must be declared with let. A const variable can't be reassigned, so TypeScript reports an error on any of these operators, and the JavaScript it writes stops with a TypeError when it reaches the assignment.

    The right side is computed first

    With an augmented assignment, the whole right side is evaluated before the operator is applied. That matters when the right side is more than a single value:

    let total = 100;
    total -= 3 * 2; // total = total - (3 * 2)
    console.log(total); // 94
    
    total *= 1 + 1; // total = total * (1 + 1), not (total * 1) + 1
    console.log(total); // 188
    

    An augmented assignment is also an expression, and its value is the new value of the variable. After let x = 4; let y = (x += 3);, both x and y are 7. You will rarely need this, but it explains why the operators can appear inside larger expressions.

    Increment and decrement

    Adding or subtracting exactly 1 is so frequent that it has its own operators. x++ does the same as x += 1, and x-- does the same as x -= 1. As separate statements, the prefix forms ++x and --x behave the same way. They differ only when the expression's value is used.

    The exercise, step by step

    The lesson walks one variable, number, through every operator and tracks its value. The values below come from running the steps.

    1. Declare number with the type number and the value 18. Use let, since every later step reassigns it.
    2. number += 8 adds 8, giving 26.
    3. number-- subtracts 1, giving 25.
    4. number /= 5 divides by 5, giving 5. In TypeScript every number is floating-point, so 25 / 5 is just 5. Had the division not been even, the result would keep its decimals: 7 / 2 is 3.5.
    5. number++ adds 1, giving 6.
    6. number *= 3 multiplies by 3, giving 18.
    7. number -= 18 subtracts 18, giving 0. The value returns to zero because the previous step left it at 18.

    The solution in TypeScript

    let number: number = 18;
    number += 8;
    number--;
    number /= 5;
    number++;
    number *= 3;
    number -= 18;
    

    A few details:

    • The annotation is not enforced at run time. : number is checked by the compiler and then erased from the JavaScript output.
    • The name number is allowed. It is also the name of a type, but types and variables live in separate namespaces, so a variable can have that name.
    • The order matters. Each step uses the value left by the one before. Moving number *= 3 earlier would change every later value.

    Why use them

    The short form is not only less typing. It makes the intent obvious: score += 10 reads as "raise score by 10", while score = score + 10 makes the reader check that both names are the same. With long names such as currentPlayerScore, that check is easy to get wrong when typing and easy to miss when reading.

    The same idea exists for a few other operators. &&=, ||= and ??= assign only in some cases: x ??= 5 stores 5 only if x is null or undefined. This lesson focuses on the arithmetic ones.

    Gotchas

    • += with strings. It concatenates: let s = "ab"; s += "cd"; makes s equal to "abcd". If the variable is typed number, the compiler reports an error for adding a string to it, although the JavaScript it still writes would concatenate (1 plus "a" gives "1a").
    • Order of the operator characters. The operator is +=, not =+. The text x =+ 5 is parsed as x = +5, which sets x to 5 instead of adding.
    • Division is not integer division. /= keeps the fractional part. To keep only the whole part, round afterwards: x = Math.floor(x).
    • Left side evaluated once. In a[i++] += 2, the index expression runs once, which is a small advantage over writing a[i++] = a[i++] + 2.

    Key takeaways

    • x op= y is shorthand for x = x op y.
    • The operators are +=, -=, *=, /=, %= and **=.
    • ++ and -- change a variable by exactly 1.
    • The variable must be declared with let.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free