JavaScript
In this tutorial we will learn about JavaScript assignment operators.
We use the assignment operator to assign value to a variable.
In JavaScript (and in other programming languages) the equal to sign = is the assignment operator and it assign the value on the right side to the variable on the left side.
=
In the following example we are assigning the value 10 to the variable x using the assignment operator.
var x = 10;
We can combine the assignment operator and arithmetic operator together to get a shorthand notation if we are operating on a given variable.
In the following example we are adding 10 to variable x and then assigning the result to the variable x.
var x = 10; //adding 10 x = x + 10; console.log(x); //this will print 20
We can get the same result by combining the operators together.
var x = 10; //adding 10 x += 10; console.log(x); //this will print 20
Following is the list of shorthand assignment operators used with arithmetic operators.
In the following example we are assigning the result of addition to a variable.
var x = 10; var y = 20; //long x = x + y console.log(x); //this will print 30
Shorthand
var x = 10; var y = 20; //shorthand x += y console.log(x); //this will print 30
In the following example we are assigning the result of subtraction to a variable.
var x = 10; var y = 20; //long x = x - y console.log(x); //this will print -10
var x = 10; var y = 20; //shorthand x -= y console.log(x); //this will print -10
In the following example we are assigning the result of division to a variable.
var x = 4; var y = 2; //long x = x / y console.log(x); //this will print 2
var x = 4; var y = 2; //shorthand x /= y console.log(x); //this will print 2
In the following example we are assigning the result of multiplication to a variable.
var x = 4; var y = 2; //long x = x * y console.log(x); //this will print 8
var x = 4; var y = 2; //shorthand x *= y console.log(x); //this will print 8
In the following example we are assigning the result of modulus to a variable.
var x = 5; var y = 2; //long x = x % y console.log(x); //this will print 1
var x = 5; var y = 2; //shorthand x %= y console.log(x); //this will print 1