- By using the increment operator (++)
- By using the addition assignment operator (+=)
- By using the Number() function
Let’s explore each…
#1 – By using the increment operator (++)
var count = 0; console.log(count); // Outputs: 0 count++; console.log(count); // Outputs: 1
How it Works
The increment operator (++) adds 1 to the value of the variable it’s applied to. This operation can be very useful in loops, counters, and many other programming situations where a value needs to be gradually increased.
- First, we declare a variable named ‘count’ and give it an initial value of 0.
- Next, we output the value of ‘count’ to the console, which will be 0, as this is the initial value we set.
- We then use the increment operator (++) to add 1 to the value of ‘count’.
- Finally, we output the value of ‘count’ again, and this time the console will display 1, as the value has been increased by the increment operator.
#2 – By using the addition assignment operator (+=)
let x = 10; x += 5;
How it works
The ‘x += 5’ is a shorthand for ‘x = x + 5’. The operator += adds the value on its right to the variable on its left and then assigns the result back to the variable.
- First, variable ‘x’ is initialized with a value ’10’.
- Then using the addition assignment operator (+=), we add ‘5’ to ‘x’. This is equivalent to ‘x = x + 5’.
- The modified value of ‘x’ is now ’15’.
#3 – By using the Number() function
let stringValue = "12"; let numberValue = Number(stringValue); numberValue++;
How it works
- First, we initialize a variable (stringValue) with a string value containing a numeric value. In the provided example, we’ve used “12”.
- Next, we use the Number() function to convert this string into a number. We store this numeric value into a new variable (numberValue).
- Lastly, we use the incremental operator (++) on the numberValue variable. This operator increases the value of numberValue by one.