0

In this function, am expecting the return value to be increment of variable value . However , i am getting original value ,

here is my function:

var num = function(){
    var a = 0;
    return a++;
}

alert(num()); //it giving the result as 0 instead of 1...why?

can anyone please explain this to me?

Arun
  • 584
  • 1
  • 6
  • 19
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

2 Answers2

4

The ++ acts after the 'return':

return a++ ==> return a, then add 1 to a

return ++a ==> add 1 to a, then return

Look at this answer.

Community
  • 1
  • 1
Don
  • 16,928
  • 12
  • 63
  • 101
1

try

var num = function(){
    var a = 0;
    return ++a;
}

++a give the value after operation a++ give the value then do the operation

Mohsen
  • 269
  • 1
  • 3