JS Assignment Operators


Assignment Operators

Ø  An assignment operator is an operator used to assign a new value to a variable, property, event, or indexer element in JavaScript programming language.

Ø  They include the following:

= (Assignment operator): assign the right operand value to the left operand. Example

let x = 100;

 

+ = (Add and Assignment operator): sum up the left and right operand values then assign the obtained result to the left operand. Example:  X += Y is equivalent to X= X + Y

let x = 10;

let y = x;

y= y+=x; //y= y+x

console.log(y); // Output=20

 

 - = (Subtract and Assignment operator): subtract the right operand value from the left operand value then assign the obtained result to the left operand. Example:  X -= Y is equivalent to X= X – Y

let x = 10;

let y = x;

y= y-=x; //y =y-x

console.log(y); //Output= 0

 

* = (Multiply and Assignment operator): multiply the left and right operand values then assign the obtained result to the left operand. Example:  X *= Y is equivalent to X= X *Y

let x = 10;

let y = x;

y= y*=x; //y =y*x

console.log(y); //Output= 100

 

/ = (Divide and Assignment operator): divide the left operand value by the right operand value then assign the obtained result to the left operand. Example:  X /= Y is equivalent to X= X /Y

let x = 10;

let y = x;

y= y/=x; //y =y/x

console.log(y); //Output = 1

 

% = (Modulus and Assignment operator):  to get the modulus of the left operand divided by the right operand then assign the resulting modulus to the left operand. Example:  X %= Y is equivalent to X= X %Y

let x = 10;

let y = 15;

y= y%=x; //y =y % x

console.log(y); //Output= 5

 

Example of all assignment operators:

let x =10;

let y=x;

let z =52;

// add and assignment operators

y= y+=x;

console.log(y); //Output =20

// Subtract and assignment operators

y= y-=x;

console.log(y); //Output =10

// Multiple and assignment operators

y= y*=x;

console.log(y); //Output =100

// Divide and assignment operators

y= y/=x;

console.log(y); //Output =1

// Modulus and assignment operators

y= z%=x;

console.log(y); //Output =2

 

 


Leave a comment
No Cmomments yet