mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-03-24 11:03:17 -04:00
feat(curriculum): Add interactive examples to How Do the Increment and Decrement Operators Work (#63241)
This commit is contained in:
@@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: how-do-the-increment-and-decrement-operators-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
If you're working with numbers and need to increase or decrease a value by one, the increment and decrement operators make the job easier. Let's break it down in a simple way.
|
||||
|
||||
@@ -17,6 +17,8 @@ There's a twist to how the increment and decrement operators work: they come in
|
||||
|
||||
Prefix (`++x`) increases the value of the variable first, then returns a new value. Postfix (`x++`) returns the current value of the variable first, then increases it:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let x = 5;
|
||||
|
||||
@@ -24,10 +26,14 @@ console.log(++x); // 6
|
||||
console.log(x); // 6
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In the code above, `++x` means "increment `x` first, then use it". So when you log `++x`, you immediately get the incremented value, which is `6`.
|
||||
|
||||
Now, let's take a look at an example using the postfix:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let y = 5;
|
||||
|
||||
@@ -35,10 +41,14 @@ console.log(y++); // 5
|
||||
console.log(y); // 6
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, `y++` means "use `y` first, then increment it". When you log `y++`, you get `5`, but `y` becomes `6` after that line of code.
|
||||
|
||||
The decrement operator does the same thing as increment, except it decreases the value by `1`. Again, there are two forms: prefix (`--x`) decreases the value of the variable first, then returns the new value. And postfix (`x--`) returns the current value first, then decreases it:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let x = 5;
|
||||
console.log(--x); // 4
|
||||
@@ -49,8 +59,12 @@ console.log(y--); // 5
|
||||
console.log(y); // 4
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
So, which should you use: prefix or postfix? In many cases, it doesn't matter which one you use. Both get the job done. However, if you're using the value immediately in an expression, the difference becomes important. Let's take a look at this example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let a = 5;
|
||||
let b = ++a;
|
||||
@@ -61,6 +75,8 @@ let d = c++;
|
||||
console.log(d); // 5 (c was incremented after assignment)
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
So, if you need the updated value right away, use prefix. If you want the current value first and you don’t care about the increment until later, go with postfix.
|
||||
|
||||
# --questions--
|
||||
|
||||
Reference in New Issue
Block a user