-6

In this code, what does 'q--' mean in the while loop?

getTotal: function () {
 
      var q = this.getItemCount(),
          p = 0;
 
      while (q--) {
        p += basket[q].price;
      }
 
      return p;
}

Is this JS shorthand? Is there an online tool that converts shorthand JavaScript into longhand? Also, why are vars q and p declared this way instead of defining them this way:

var q = this.getItemCount(); var p = 0;

Maria Blair
  • 199
  • 2
  • 9
  • 2
    That's the post-decrement operator, common to many languages that copied C syntax. – Pointy Dec 30 '16 at 22:12
  • `--` means decrementing. It will subtract 1 from `q` with every loop. `q--` == `q = q-1` – kind user Dec 30 '16 at 22:12
  • [Here is a handy reference for JavaScript expressions.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators) – Pointy Dec 30 '16 at 22:13
  • 1
    @leok: the loop is fine so long as `q` is an int and `q>0` at the start. – dandavis Dec 30 '16 at 22:14
  • 2
    This should explain your "--" question a little ways down the first answer http://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript and this should help with your var question: http://stackoverflow.com/questions/694102/declaring-multiple-variables-in-javascript – Eric G Dec 30 '16 at 22:16

3 Answers3

1

as you can tell q is a variable with the number of items and the -- is Decrement Operator it just subtracts one form q until reaches 0.

This is works because in javaScript 0 == false and it will get out of the loop when q reaches 0.

H. J. Rhenals
  • 125
  • 3
  • 7
1

It's the decrement operator. The value of q is decreased by 1 each time q-- is evaluated but, importantly, the value is returned before the decrement.

So, the loop above will continue until q=1 but the value used inside the loop during this final iteration will be q=0.

In layman's terms: q-- means "Give me the value of q then decrease it by 1 directly afterwards".

Paul
  • 617
  • 4
  • 18
  • Thank you! Makes sense. – Maria Blair Dec 30 '16 at 22:27
  • 1
    Specifically `while( q--){...}` and `for( ; q--;){...}` say to execute the loop `q` times, but within the loop q can be used as a zero based index. It is often an optimization borrowed from C to traverse an array backwards after initializing `q` to the array length; – traktor Dec 31 '16 at 00:40
0

Here, q-- means "subtract 1 from q and keep its old value q". The variables are declared in the shorthand method to reserve the size of the page and therefore its loading time.

Wais Kamal
  • 4,312
  • 2
  • 11
  • 26