前置と後置のインクリメント/デクリメントを理解する
このステップでは、JavaScript における前置と後置のインクリメント/デクリメント演算子の違いを学びます。これらの演算子は似ているように見えますが、式の中で使用されるときの振る舞いは異なります。
arithmetic.html ファイルを開き、<script> セクションを次のコードで更新します。
<script>
// Postfix Increment (x++)
let a = 5;
let b = a++;
console.log("Postfix Increment:");
console.log("a =", a); // a is incremented after the value is assigned
console.log("b =", b); // b gets the original value of a
// Prefix Increment (++x)
let x = 5;
let y = ++x;
console.log("\nPrefix Increment:");
console.log("x =", x); // x is incremented before the value is assigned
console.log("y =", y); // y gets the incremented value of x
// Similar concept applies to decrement operators
let p = 10;
let q = p--;
console.log("\nPostfix Decrement:");
console.log("p =", p); // p is decremented after the value is assigned
console.log("q =", q); // q gets the original value of p
let m = 10;
let n = --m;
console.log("\nPrefix Decrement:");
console.log("m =", m); // m is decremented before the value is assigned
console.log("n =", n); // n gets the decremented value of m
</script>
この HTML ファイルをウェブブラウザで開き、開発者コンソールを確認すると、次のような出力例が表示されます。
Postfix Increment:
a = 6
b = 5
Prefix Increment:
x = 6
y = 6
Postfix Decrement:
p = 9
q = 10
Prefix Decrement:
m = 9
n = 9
理解すべき要点:
- 後置
x++: 元の値を返してからインクリメントします
- 前置
++x: まずインクリメントしてから新しい値を返します
- 同じ原則がデクリメント演算子
x-- と --x にも適用されます
- この違いは、演算子が式や代入文の中で使用されるときに重要になります