Addition Assignment (+=)
You'll learn: How to use the += operator to add and reassign a variable's value in a single, concise step.
What Is Addition Assignment?
The addition assignment operator (+=) combines two operations into one: it adds a value to a variable and then stores the result back in that same variable. Instead of writing the variable name twice, you write it once and use += as a shortcut.
Think of it like updating your bank account balance. Rather than saying "my balance equals my old balance plus my deposit," you simply say "add this deposit to my balance." The += operator does exactly that.
How It Works
Here's the traditional way to add and reassign:
let score = 10;
score = score + 5; // score is now 15
With +=, you can write the same thing more concisely:
let score = 10;
score += 5; // score is now 15
Both versions produce identical results, but += is cleaner and faster to type.
Practical Examples
let total = 100;
total += 50; // total is now 150
total += 25; // total is now 175
let count = 0;
count += 1; // increment by 1, count is now 1
count += 10; // count is now 11
String Concatenation with +=
Remember that + works with strings too, so += can append text:
let message = "Hello";
message += " World"; // message is now "Hello World"
Key Takeaway: Use += to add a value to a variable and update it in one concise operation—it's cleaner than writing variable = variable + value.