Return and the ++ operator

I was going through Functional Programming and this thing had me pulling my hair out. Basically,

return ++val;

worked but

return val++;

did not. Apparently the return statement in the second case was simply returning val without performing the increment. I knew that in some cases the position of the increment operator had ramifications, but this one seems pretty weird to me–is this expected behavior?

yes this is the normal behaviour

Prefix = ++val
Postfix = val++

return val++ // = val

return ++val // = val + 1

to get val + 1 for val++

val++
return val
1 Like

val++ will incremet the value once the val is used.while ++val will increment the value before it is used.
For example:

let val=5;
console.log(val++); //prints 5
console.log(val);//prints 6 because once the value of val is printed and now it is updated
console.log(++val)//prints 7 because it updates value right after the statement ++val.

Hope it helps.

1 Like