javascriptjqueryoperators

What does minus equals mean in JavaScript?


What does the minus equals below -= mean/do?

$('#wrapper').animate({
    backgroundPosition: '-=2px'
})();

Thank you


Solution

  • Adil has answered this but I always think it is useful to visualise problems and relate them to others.

    The following two pieces of code have the same effect:

    var a = 20;
    a = a - 5;
    

    and

    var a = 20;
    a -= 5;
    

    In both cases a now equals 15.

    This is an assignment operator, what this means is that it applies whatever is on the right side of the operator to the variable on the left. See the following table for a list of assignment operators and their function:

    Operator |  Example |  Same as    |  Result
    ______________________________________________
      =      |  a = 20  |             |  a = 20
      +=     |  a += 5  |  a = a + 5  |  a = 25
      -=     |  a -= 5  |  a = a - 5  |  a = 15
      *=     |  a *= 5  |  a = a * 5  |  a = 100
      /=     |  a /= 5  |  a = a / 5  |  a = 4
      %=     |  a %= 5  |  a = a % 5  |  a = 0
    

    You also have the increment and decrement operators:

    ++ and -- where ++a and --a equals 21 and 19 respectively. You will often find these used to iterate for loops.

    Depending on the order you will do different things.

    Used with postfix (a++) notation it returns the number first then increments the variable:

    var a = 20;
    console.log(a++); // 20
    console.log(a); // 21
    

    Used with prefix (++a) it increments the variable then returns it.

    var a = 20;
    console.log(++a); // 21
    console.log(a); // 21