-2
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!

user1142130
  • 1,617
  • 3
  • 20
  • 34
  • it works as a prefix. Change it to `++map[i]` - read why here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#description – Randy Casburn Nov 28 '21 at 16:57
  • Common across many languages. – Randy Casburn Nov 28 '21 at 16:58
  • 1
    I did not downvote you and don't understand why someone would. I suspect it is because of [obligations before asking](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users/261593#261593). – Randy Casburn Nov 28 '21 at 17:19
  • Does this answer your question? [What does this symbol mean in JavaScript?](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript) – Randy Casburn Nov 28 '21 at 17:20

2 Answers2

2

This is because map++ only increments after the line runs, if you use ++map it will increment it before, map + 1 will do the same thing.

let a = 1
let b = 1
console.log(a + b++) // 2

let a = 1
let b = 1
console.log(a + ++b) // 3

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#description

2

++ 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>
hirad davari
  • 103
  • 6