To increment a value in Javascript there are four ways. The most common and simple of all is using the operator ++
that will add +1
value of variable. See example below:
var valor = 2;
valor++;
console.log(valor); // Resultado: 3
The second way is also using the operator ++
, but here you must use it before the variable. The difference this way for the first one is that in the first form the value is incremented only after it has been used. See the example below:
var valor = 2;
console.log(valor++); // Imprime 2 porque o incremento vem depois.
console.log(++valor); // Imprime 4 porque o incremento vem antes.
The third way is using the operator +=
which will increment a value X to the variable. In this form you yourself specify the value that will be added, being quite different from the first way where the sum value is 1
obligatorily.
var valor = 2;
valor += 5;
console.log(valor); // Resultado: 7
The last form is by assigning to the variable its own value added to another value you want, using the summation operator.
var valor = 3;
valor = valor + 1;
console.log(valor); // Resultado: 4
As you saw in the example above, both the third and fourth forms are equivalent. So if you want to make your code smaller and more beautiful, use the third way.
Now take this last example which may be what you want:
let value = 0;
function incrementar() {
document.getElementById("display").innerHTML = `Value: ${++value}`;
}
<input type="button" onclick="incrementar();" value="Incrementar"/>
<div id="display" style="padding-top: 15px;">Value: 0</div>