red house 87
red house 87

Reputation: 2415

Update value not incrementing in Javascript

I am trying to increment a value by one each time but its not working. My variable currentValue gives me 0 as expected but when i try increment it using var newValue = currentValue ++; it still gives me 0.

function updateClicks(e, maxValue) {
    var buttonClicked = e.target;
    addClass("clicked", buttonClicked);
    var counterBox = buttonClicked.nextElementSibling;

    var currentValue = buttonClicked.value;
    console.log(currentValue);

    var newValue = currentValue++;
    console.log(newValue);
}

What am I doing wrong here?

Upvotes: 1

Views: 1449

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

If you want to affect the incremented value you have to use pre increment operator like :

var newValue = ++currentValue;

Since currentValue++ (post increment) will increment the currentValue but after assigning it to the newValue variable.

  • pre-increment : (++currentValue) will adds one to the value of currentValue then returns currentValue.
  • post-increment : (currentValue++) will returns currentValue then adds one to it.

Hope this helps.

var currentValue = 0;
console.log('Increment using pre increment : '+(++currentValue));
console.log('pre increment return : '+currentValue);

console.log('-----------------------------------');

var currentValue = 0;
console.log('Increment using post increment : '+(currentValue++));
console.log('post increment return : '+currentValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68665

It will give you 0 for first time. Why ?
++ (post increment) operator - returns the value then increments it's value. Example

var a = 4;
var b = a++; // Here it assigns 4 to b, then increments it's value
console.log(a); // 5
console.log(b); // 4

You must use the pre increment form

  var a = 4;
  var b = ++a; // Here it increments it's value then assigns it to b
  console.log(a); // 5
  console.log(b); // 5

Upvotes: 1

Sergeon
Sergeon

Reputation: 6788

try:

var newValue = ++currentValue;

Upvotes: 0

Related Questions