Skip to main content

Assignment Operators

In this tutorial, we're going to discuss a fundamental concept in TypeScript - Assignment Operators. These are an integral part of the language and are used to assign values to variables. If you're new to TypeScript or programming in general, don't worry! We'll break down everything step by step.

What are Assignment Operators?

Assignment operators, as the name suggests, are used to assign values to variables. The most common assignment operator that you might already be familiar with is =. For instance, let x = 10;. Here, = is the assignment operator.

In addition to this basic assignment operator, TypeScript supports a variety of compound assignment operators that perform an operation and an assignment in a single step.

List of Assignment Operators

Here's a list of all assignment operators in TypeScript:

  • =: Assigns the value of the right operand to the left operand. E.g., x = y assigns the value of y to x.
  • +=: Adds the right operand to the left operand and assigns the result to the left operand. E.g., x += y is equivalent to x = x + y.
  • -=: Subtracts the right operand from the left operand and assigns the result to the left operand. E.g., x -= y is equivalent to x = x - y.
  • *=: Multiplies the right operand with the left operand and assigns the result to the left operand. E.g., x *= y is equivalent to x = x * y.
  • /=: Divides the left operand with the right operand and assigns the result to the left operand. E.g., x /= y is equivalent to x = x / y.
  • %=: Calculates the modulus of the left operand with the right operand and assigns the result to the left operand. E.g., x %= y is equivalent to x = x % y.

Examples of Assignment Operators

Let's look at some examples to understand how these operators work:

let x = 10; // x is 10
x += 5; // x is now 15
x -= 3; // x is now 12
x *= 2; // x is now 24
x /= 4; // x is now 6
x %= 2; // x is now 0

Conclusion

And that's it! You've learned about assignment operators in TypeScript. Remember, these operators are fundamental to programming, and you'll regularly see them in code. So make sure you understand how they work and when to use them.

Keep coding and exploring more with TypeScript!