JavaScript Assignment Operators

Bookmark and Share

Assignment Operator (=)

The = operator expects its left-side operand to be either a variable, the element of an array, or a property of an object. It expects its right-side operand to be an arbitrary value of any type.

The = operator assigns the value on the right to the variable, element, or property on the left.

	var x = 10;
	console.log(x);			// 10

The value of an assignment expression is the value of the right-side operand.

	var x;
	console.log(x = 10);	// 10

When multiple assignment operators appear in an expression, they are evaluated from right to left.

	x = y = z = 10;
	console.log(x);		// 10
	console.log(y);		// 10
	console.log(z);		// 10

Assignment with Operation

In JavaScript, assignment operators combine assignment with some other operation. For example: a += b is equivalent to a = a + b, similar operators as following:

	var x = 10;			
	console.log (x += 5);	// 15
	var x = 10;		
	console.log (x -= 5);	// 5
	var x = 10;				
	console.log (x *= 5);	// 50
	var x = 10;
	console.log (x /= 5);	// 2
	var x = 10;
	console.log (x %= 5);	// 0
	var x = 10;
	console.log (x += '5');	// 105, String concatenation
	var x = 10;
	console.log (x -= '5');	// 5, Numeric Subtraction

Note: The + operator is a special one: it gives priority to string operands over numeric operands. If either operand is a string, the other operand is converted to a string.

On the other hand, if used with nonnumeric operands, the - operator attempts to convert them to numbers.

 

Related Tutorials