Home Courses Assignment Operators Explained

Assignment Operators Explained

What are Assignment Operators?

Assignment operators are used to:

  1. Assign values to variables
  2. Update existing values

Example:

let a = 10; // = is assignment operator


Why Use Assignment Operators?

  1. Helps update values easily
  2. Makes code shorter and cleaner
  3. Improves performance in large applications


List of Assignment Operators

Operator
=Assign
+=Add and assign
-=Subtract and assign
*=Multiply and assign
/=Divide and assign
%=Modulus and assign
**=Exponentiation and assign
<<=Left shift and assign
>>=Right shift and assign
>>>=Unsigned right shift and assign
&=Bitwise AND and assign
`=`
^=Bitwise XOR and assign


Basic Example

let a = 10;
console.log(a); // 10


Updating Value (Normal Way)

let a = 10;
let b = 5;

a = a + b; // 15


Using Assignment Operator (Better Way)

let a = 10;
let b = 5;

a += b; // 15
  1. Same result as a = a + b
  2. Shorter and more efficient


Other Examples

Subtract and Assign

a -= b; // 10 - 5 = 5


Multiply and Assign

a *= b; // 10 * 5 = 50


Divide and Assign

a /= b;


Modulus and Assign

a %= b;


Exponentiation and Assign

a **= b; // 10^5


Function Example from Code

function operations() {
let a = 10;
let b = 5;

a **= b;
console.log(a);
}

Important Concept

Difference

a = a + b; // uses 2 operators
a += b; // uses 1 operator
  1. += is preferred in large projects
  2. Improves readability and performance


Multiple Operations Example

let a = 10;
let b = 5;

a += b; // 15
a -= b; // 10
a *= b; // 50


Bitwise Assignment Operators (Basic Idea)

  1. Work on binary (0 and 1)
  2. Rarely used in normal projects

Examples:

a &= b; // AND
a |= b; // OR
a ^= b; // XOR


Shift Assignment Operators

  1. Also based on binary shifting
a <<= 1; // left shift
a >>= 1; // right shift
a >>>= 1; // unsigned right shift
  1. Mostly used in low-level operations


Important Notes

  1. Use +=, -=, *= in real projects
  2. Bitwise and shift operators are rarely used
  3. Assignment operators make code cleaner


Share this lesson: