2

Let's say this is my factory function to generate an object.

const generateObjectWithId = (id,value) => (
 {id,value}
);

I have declared an Id before I generated the object and then I incremented it using ++

let currentId = 0;
const object = generateObjectWithId(currentId++,"sample");

Result:

console.log(currentId) => 1
console.log(object) => {id:0,value:"sample"}

currentId got incremented to 1 but the object I received from the factory function is with id 0.

I've fixed it with incrementing the currentId before passing in the parameter and worked right now.

My fix:

let currentId = 0;
currentId++; //or currentId = currentId + 1;
const object = generateObjectWithId(currentId,"sample");

But I need someone's help to explain me why incrementing inside the parameter won't work.

Thanks a lot.

Kevin Moe Myint Myat
  • 1,916
  • 1
  • 10
  • 19

3 Answers3

2

currentId++, this increments the counter after the passing while ++currentId increments the counter and then pass it

Alok Takshak
  • 282
  • 1
  • 6
0

It will increment the index after passing it to the function. If you used ++currentId it should work.

jvda
  • 286
  • 2
  • 7
0

currentId++ means increment after the execution. I think what you need is ++currentId, which means increment then execute.

TTY112358
  • 134
  • 6