+ 2

Javascript Problem with function

function y(x){ x= x+1; return x++; } console.log(y(2)); Why it's returning 3? X= 2 Then, x= x+1 //x=3 Then, x++; // x = 4? Help me please

21st Jun 2022, 1:37 PM
Sachin
Sachin - avatar
4 odpowiedzi
+ 4
In your function you type 5 but in comments 1, I think you make typo and meant x = x + 1 Reason why it return 3 not 4 is because of how increment work. When you type x++ it will add 1 to x but after this line of code end. So when you return, value is 3, but after return it will be 4 (this will never run because return exit from function) Check my code to understand better https://code.sololearn.com/W56Ig5vNOH7R/?ref=app
21st Jun 2022, 2:05 PM
PanicS
PanicS - avatar
+ 2
PanicS Thanks now I understand.🔮
21st Jun 2022, 2:08 PM
Sachin
Sachin - avatar
+ 2
Sachin x++ post increment first assign then increment by 1 ++x pre increment first increment by 1 then assign So if there is ++x then x = 4
21st Jun 2022, 2:13 PM
A͢J
A͢J - avatar
+ 2
A͢J Thanks
21st Jun 2022, 3:16 PM
Sachin
Sachin - avatar