Incremental operator ++ used to increase the existing variable value by 1 (x = x + 1). Increment operators in JS programming are used in For Loop, While loop, and Do While loops.
- ++i (Pre increment): It will increment the value of i even before assigning it to the variable i.
- i++ (Post-increment): The operator returns the variable value first (i.e, i value) then only i value will incremented by 1.
JavaScript auto-increment variable example code
Here is the HTML example code of auto-increment x and y variables in JS.
<!DOCTYPE html>
<html>
<body>
<script>
var x = 0;
//pre-increment
++x;
console.log(x);
//post-increment
var y = 1;
y++;
console.log(y);
</script>
</body>
</html>
Output:
Auto increment variable value by 2
Here is another example.
<script>
var x = 0;
x= 2+x;
console.log(x);
</script>
Do comment if you have any doubts and suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version