Skip to content
Advertisement

Why do I get different answer when using `++` vs using `+1` [closed]

let arr = [3, 5, 5];
let map = {};

for (let i of arr) {
  if(map[i]){
    map[i] = map[i]++ //<== doesn't work correctly with ++
  }else{
    map[i] = 1
 }
}
console.log(map);
//outputs {3: 1, 5: 1}

Code above outputs {3: 1, 5: 1}, which is incorrect. 5 should be 2, not 1

let arr = [3, 5, 5];
let map = {};

for (let i of arr) {
  if(map[i]){
    map[i] = map[i]+1 // <== here it works correctly with +1
  }else{
    map[i] = 1
  }
}
console.log(map);
//outputs {3: 1, 5: 2}

Code above outputs {3: 1, 5: 2} correct solution, but why the difference between the two solutions? I thought the ++ is equivalent to +1. But map[i]++ and map[i]+1 give different solutions!

Advertisement

Answer

++ after a variable by definition adds one to the variable and returns the unchanged value

b=3;
c=b++; //c = 3, b = 4

you can put ++ before a variable to return the value

b=3;
c=++b; //c = 4 b = 4

EDIT: following Randy Casburn’s request in the comments, here’s a snippet:

var b1 = 3;
var c1 = b1++;
document.getElementById('res1').innerHTML = 'b1 = '+b1+' & c1 = '+c1;

var b2 = 3;
var c2 = ++b2;
document.getElementById('res2').innerHTML = 'b2 = '+b2+' & c2 = '+c2;
<p id="res1"></p>
<p id="res2"></p>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement