Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minus equals in javascript - What does it mean?

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

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

Thank you

like image 817
David Van Staden Avatar asked Mar 27 '13 16:03

David Van Staden


People also ask

What is minus in JavaScript?

Subtraction (-) The subtraction operator ( - ) subtracts the two operands, producing their difference.

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.

What does += mean in JavaScript?

The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible.

What is == and === in JavaScript?

== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. Checks the equality of two operands without considering their type. Compares equality of two operands with their types.


2 Answers

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
like image 139
George Reith Avatar answered Sep 21 '22 13:09

George Reith


The operator -= (Subtraction assignment) will subtract the given value from the already set value of a variable.

For example:

var a = 2;
a -= 1;
//a is equal to 1
like image 30
Adil Avatar answered Sep 20 '22 13:09

Adil