Increment (++) and Decrement (--)
The increment ++ and decrement -- operators add or subtract 1 from a variable. They can be used in prefix form (before the variable) or postfix form (after the variable).
Syntax
++variable // Prefix increment
variable++ // Postfix increment
--variable // Prefix decrement
variable-- // Postfix decrementPrefix vs Postfix
The key difference is when the value is returned:
- Prefix (
++x): Increments first, then returns the new value - Postfix (
x++): Returns the current value, then increments
Examples
Basic usage:
let x = 5; x++; // x is now 6 print(x); // Output: 6 let y = 10; y--; // y is now 9 print(y); // Output: 9
Prefix vs Postfix difference:
let a = 5; let b = ++a; // a becomes 6, then b = 6 print(a, b); // Output: 6 6 let c = 5; let d = c++; // d = 5, then c becomes 6 print(c, d); // Output: 6 5
In Loops
Commonly used in for loops:
// Traditional C-style for loop with increment
for (let i = 0; i < 5; i++) {
print(i); // Output: 0, 1, 2, 3, 4
}
// Counting down
for (let i = 5; i > 0; i--) {
print(i); // Output: 5, 4, 3, 2, 1
}Game Use Cases
Counting lives:
let lives = 3;
fn takeDamage() {
lives--;
if (lives <= 0) {
print("Game Over!");
} else {
print("Lives remaining:", lives);
}
}
takeDamage(); // Lives remaining: 2
takeDamage(); // Lives remaining: 1
takeDamage(); // Game Over!Collecting points:
let score = 0;
fn collectCoin() {
score++;
print("Score:", score);
}
fn collectBonus() {
// Bonus gives 10 points
for (let i = 0; i < 10; i++) {
score++;
}
print("Bonus collected! Score:", score);
}Lvalue targets (v0.1.5+)
The operand can be any assignable location — not just a bare variable:
let arr = [1, 2, 3];
arr[0]++; // arr is now [2, 2, 3]
class Counter {
let n = 0;
}
let c = new Counter();
c.n++; // field increment works
++c.n; // prefix form tooRequirements
- The operand must be an lvalue — variable, index, or field (v0.1.5+)
- The value must be numeric (int or float)
- Float values are incremented by 1.0
- Cannot be used on const variables
Restrictions
// These will cause errors:
let x = 5++;
// ^^ Error: not an assignable target
let y = (2 + 3)++;
// ^^ Error: not an assignable target
const z = 10;
z++; // Error: cannot modify const variableSee Also
- for loops — Using ++ in loop control
- while loops — Manual iteration control
- Operators — All available operators