Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSLint Error: Unexpected '--'

I'm getting two errors in a JS file, both "Unexpected '--'." It's in code for mousewheel scrolling (both times as this.addEventListener( types[--i], handler, false ); ). I've never seen this --i syntax anywhere before. What is it, and how should I correct it to be proper, and make JSLint happier?

(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
$.event.special.mousewheel = {
    setup: function() {
        var i;
        if ( this.addEventListener ) {
            i = types.length;
            while ( i >= 0 ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },

    teardown: function() {
        if ( this.removeEventListener ) {
            i = types.length;
            while ( i >= 0 ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};
like image 784
Keefer Avatar asked Dec 22 '22 02:12

Keefer


1 Answers

--n syntax decrements a variable. Slightly more common, that you may have seen is n++, which is similar, but increments a variable.

The -- or the ++ can appear before or after the variable, and there is a subtle difference. When it come before, it alters the value and then returns the altered value. When it comes after, it returns the original value. When using the value directly, this makes a difference.

var i;

// affix
i = 1; console.log(i++, i) // 1 2
i = 1; console.log(i--, i) // 1 0

// prefix
i = 1; console.log(++i, i) // 2 2
i = 1; console.log(--i, i) // 0 0

Note how the value of the prefixed increment or decrement expression returns the same value for i after the operation, where the affix version doesn't.

So, long story short, JSLint doesn't like prefixed increment operators very much. But this should be equivalent:

while ( i >= 0 ) {
  i -= 1;
  this.removeEventListener( types[i], handler, false );
}

By not using the direct result of decrement operation, it ceases to matter how that operator works and what it returns. It's also a bit more explicit, and JSLint likes explicit.

like image 92
Alex Wayne Avatar answered Dec 29 '22 00:12

Alex Wayne