ProgramGuru

Assignment Operators

Learn Assignment Operators

Assignment stores a new value in a mutable binding. Compound assignments combine an operation and a reassignment.

In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.

What you’ll learn

  • Explain the main rule behind assignment operators.
  • Predict the result of the complete runnable TypeScript example.
  • Recognize one common mistake and correct it.

Understand the concept

For example, score += 5 is shorthand for score = score + 5. Other compound assignments include -=, *=, /= and %=, while ++ increments by one. TypeScript checks that the new value is assignable to the binding type.

Run a complete TypeScript example

Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.

TypeScript code

let balance: number = 100;
 balance += 50;
 balance -= 20;
 console.log(balance);

Verified output

130

How to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.

Trace the execution

The initial 100 grows to 150 and then falls to 130. The variable must be declared with let because it is reassigned.

Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.

Common mistakes and how to avoid them

Attempting balance += "20" produces an unwanted string operation or checker concern depending on context. Parse external input first.

Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.

Practice it yourself

Add a balance *= 2 operation and predict the new final balance before running.

Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.

Check your understanding

What does balance += 50 mean?
Choose one answer. You can try again.

Answer and explanation

Assign balance + 50 back to balance.

Compound assignment changes the stored binding value.

Review the key idea

Assignment Operators: For example, score += 5 is shorthand for score = score + 5.

Compound assignment changes the stored binding value.

Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Comparison Operators →