JavaScript
x
13
13
1
let arr = [3, 5, 5];
2
let map = {};
3
4
for (let i of arr) {
5
if(map[i]){
6
map[i] = map[i]++ //<== doesn't work correctly with ++
7
}else{
8
map[i] = 1
9
}
10
}
11
console.log(map);
12
//outputs {3: 1, 5: 1}
13
Code above outputs {3: 1, 5: 1}
, which is incorrect. 5 should be 2, not 1
JavaScript
1
13
13
1
let arr = [3, 5, 5];
2
let map = {};
3
4
for (let i of arr) {
5
if(map[i]){
6
map[i] = map[i]+1 // <== here it works correctly with +1
7
}else{
8
map[i] = 1
9
}
10
}
11
console.log(map);
12
//outputs {3: 1, 5: 2}
13
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
JavaScript
1
3
1
b=3;
2
c=b++; //c = 3, b = 4
3
you can put ++ before a variable to return the value
JavaScript
1
3
1
b=3;
2
c=++b; //c = 4 b = 4
3
EDIT: following Randy Casburn’s request in the comments, here’s a snippet:
JavaScript
1
7
1
var b1 = 3;
2
var c1 = b1++;
3
document.getElementById('res1').innerHTML = 'b1 = '+b1+' & c1 = '+c1;
4
5
var b2 = 3;
6
var c2 = ++b2;
7
document.getElementById('res2').innerHTML = 'b2 = '+b2+' & c2 = '+c2;
JavaScript
1
2
1
<p id="res1"></p>
2
<p id="res2"></p>