Example 1 — In a for loop
Classic counter.
JavaScript
for (let i = 0; i < 3; i++) console.log(i);How It Works
- i++ runs after each body.
++ adds one; -- subtracts one. Prefix (++x) updates then yields the new value. Postfix (x++) yields the old value then updates.
let n = 1;
console.log(n++);
console.log(n);
console.log(++n);Classic counter.
for (let i = 0; i < 3; i++) console.log(i);-- counts down.
let n = 3;
console.log(--n);Readability tip.
let n = 0;
n += 1;
console.log(n);CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful