Skip to content
Advertisement

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

JavaScript

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

JavaScript

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

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

JavaScript

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

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement