Increment and Decrement
When modifying numeric variables, you will often need to increase or decrease their values by a specific amount. While you can write out the full addition assignment, JavaScript provides convenient shorthand operators.
The += and -= Operators
Like Python and many other languages, JavaScript uses the += operator to add a value to an existing variable, and -= to subtract a value.
let currentLimit = 10;
currentLimit += 5; // Adds 5. The value is now 15
currentLimit -= 2; // Subtracts 2. The value is now 13
The ++ and -- Operators
When you only need to increment or decrement a value by exactly 1—which is incredibly common in loops and counters—JavaScript provides the ++ and -- operators.
let priorityScore = 4;
priorityScore++;
console.log(priorityScore); // 5
priorityScore--;
console.log(priorityScore); // 4
Note: You can only use these shorthand operators on variables declared with let or var. Variables declared with const cannot be reassigned.
Practical Example
You might need to closely monitor the status of message deliveries. If a webhook returns a failure status, you need to increment a running failure tally.
// The current count of messages that failed to deliver today
let numFailedMessages = 1336;
// A new failure report comes in, increment the count by exactly 1
numFailedMessages++;
console.log(numFailedMessages + " failed messages");