TypeScript Tutorial
TypeScript Operators
Arithmetic, comparison, and assignment operators work on values. Precedence decides what runs first.
Arithmetic
+, -, *, and / add, subtract, multiply, and divide.% is remainder after division. TypeScript number is floating-point, so10 / 3 keeps a fraction. That is different from C++ integer division.
Example
console.log(10 + 3);
console.log(10 - 3);
console.log(10 * 3);
console.log(10 / 3);
console.log(10 % 3);10 / 3 is about 3.333. 10 % 3 is 1: three goes into ten three times, remainder one. Use Math.floor(10 / 3) when you want the whole-number quotient3.
Run the listings in /typescript/try with Try it in TypeScript. tsc compiles them there. Do not use the Python editor at /try or the C++ editor at /cpp/try.
Increment and decrement
++ adds one. -- subtracts one. Written as a statement, n++ and++n both change n by one. This tutorial uses them on their own line so prefix and postfix do not matter yet.
After let n: number = 5;, the statement n++; leaves n equal to 6.n--; would take it back to 5.
Comparison
Comparisons produce a boolean. console.log prints that as true orfalse. Prefer === to test equality. A single = assigns; it does not compare. == also exists, but it coerces types: "7" == 7 is true."7" === 7 is false. Use ===.
| Operator | Meaning |
|---|---|
=== | equal (same type and value) |
!== | not equal |
< | less than |
> | greater than |
<= | less than or equal |
>= | greater than or equal |
Example
const a: number = 7;
const b: number = 4;
console.log(a === b);
console.log(a !== b);
console.log(a > b);
console.log(a < b);Write === and !== in new code. == and != convert before they compare, which hides bugs. tsc will still compile ==; the mistake is logical, not a syntax error.
Logic
&& is and: both sides must be true. || is or: at least one side is true.! is not: it flips true and false. Use parentheses when you mix them so the intended grouping is obvious.
Example
const n: number = 8;
console.log(n > 0 && n < 10);
console.log(n < 0 || n > 100);
console.log(!(n === 8));Compound assignment
+= adds and stores. -=, *=, /=, and %= work the same way. n += 2 means n = n + 2.
Example
let n: number = 10;
n++;
n += 5;
n *= 2;
console.log(n);Precedence
Multiplication and division run before addition and subtraction. 2 + 3 * 4 is 14, not20. Parentheses override the default: (2 + 3) * 4 is 20. When a line looks busy, add parentheses even if the default would match what you meant.
Next: string, where + concatenates text instead of adding numbers.