Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Why do I get different answer when using `++` vs using `+1`
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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

++ 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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!