Sethen
Sethen

Reputation: 11348

Property of Function not increasing properly?

I am practicing some various JavaScript techniques, namely function properties. Here is something that has me scratching my head a little.

//property of the q0 function
q0.unique = 0;


function q0() {

return q0.unique++;

}

console.log(q0()); //returns 0 
console.log(q0()); //returns 1
console.log(q0()); //returns 2
console.log(q0()); //returns 3

Shouldn't the first call to the function return 1? Why is it returning 0? q0.unique is already set to 0?

Upvotes: 1

Views: 45

Answers (4)

gdoron
gdoron

Reputation: 150273

There are two increment operators:

var++ // increment  the variable ---after--- the operation.  
++var // increment  the variable ---before-- the operation.

Example:

var x = 0;

alert(x++) // 0
alert(x)   // 1
alert(++x) // 2

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340883

You are confusing pre- and post-incrementation. Given:

var unique = 0;

var x = unique++ will assign current value of unique (0) while var x = ++unique will assign value of unique after incrementation (1). In both cases the value of unique is 1 after all.

What you want is:

function q0() {
  return ++q0.unique;
}

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382274

The postfix increment operator returns the value before the increment.

var a = 0;
var b = a++;
// now a==1 and b==0

The best way to recall it is to read a++ as give the value and then increment.

If you want to return the value after the increment, use

return ++q0.unique;

Reference

Upvotes: 2

user1726343
user1726343

Reputation:

That would be true if your code was:

function q0() {

return ++q0.unique;

}

The suffixed ++ returns the current value then increments. With a prefixed ++ it's the other way around.

Upvotes: 3

Related Questions