TypeScript - Operators
TypeScript - Operators
Section titled “TypeScript - Operators”What is an Operator?
Section titled “What is an Operator?”Operators are special symbols or keywords that perform operations on one or more values, called operands. They are fundamental for manipulating data and controlling program flow.
Consider the expression:
let sum = 5 + 3; // 8Here, 5 and 3 are operands, + is the addition operator, and = is the assignment operator.
TypeScript inherits most of its operators from JavaScript and groups them into categories:
- Arithmetic Operators
- Comparison (Relational) Operators
- Logical Operators
- Assignment Operators
- Bitwise Operators
- String Operators
- Conditional (Ternary) Operator
- Type Operators
- Nullish Coalescing and Optional Chaining Operators
Arithmetic Operators
Section titled “Arithmetic Operators”Perform standard mathematical calculations. Assume let a = 10; let b = 4;
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Addition | a + b | 14 |
- | Subtraction | a - b | 6 |
* | Multiplication | a * b | 40 |
/ | Division | a / b | 2.5 |
% | Modulus (Remainder) | a % b | 2 |
** | Exponentiation (ES2016) | a ** b (10^4) | 10000 |
++ | Increment (adds 1) | a++ (post) or ++a (pre) | 11 |
-- | Decrement (subtracts 1) | b-- (post) or --b (pre) | 3 |
Comparison (Relational) Operators
Section titled “Comparison (Relational) Operators”Compare two operands and return a boolean value (true or false). Assume let x = 5; let y = '5'; let z = 10;
Important: Always prefer strict equality/inequality (===, !==) over loose equality (==, !=) to avoid unexpected type coercion.
| Operator | Description | Example | Result |
|---|---|---|---|
> | Greater than | z > x | true |
< | Less than | x < z | true |
>= | Greater than or equal to | x >= 5 | true |
<= | Less than or equal to | z <= 5 | false |
=== | Strict Equality (value and type) | x === 5 | true |
=== | Strict Equality | x === y | false (number vs string) |
!== | Strict Inequality (value or type) | x !== y | true |
== | Loose Equality (value, after type coercion) | x == y | true (string ‘5’ coerced to number 5) |
!= | Loose Inequality | x != 5 | false |
Logical Operators
Section titled “Logical Operators”Combine boolean expressions. Assume let p = true; let q = false;
| Operator | Description | Example | Result |
|---|---|---|---|
&& | Logical AND (true if both operands are true) | p && q | false |
|| | Logical OR (true if at least one operand is true) | p || q | true |
! | Logical NOT (inverts boolean value) | !p | false |
Logical operators use short-circuiting: && stops evaluating if the first operand is false, || stops if the first is true.
Assignment Operators
Section titled “Assignment Operators”Assign values to variables.
| Operator | Example | Equivalent To |
|---|---|---|
= | let count = 10; | Simple assignment |
+= | count += 5; | count = count + 5; |
-= | count -= 2; | count = count - 2; |
*= | count *= 3; | count = count * 3; |
/= | count /= 4; | count = count / 4; |
%= | count %= 3; | count = count % 3; |
**= | count **= 2; | count = count ** 2; |
Bitwise Operators
Section titled “Bitwise Operators”Operate on the binary representation of numbers. Less common in typical web development but used in specific scenarios (e.g., graphics, low-level operations). Assume let A = 5 (0101); let B = 3 (0011);
| Operator | Description | Example | Result (Binary) | Result (Decimal) |
|---|---|---|---|---|
& | Bitwise AND | A & B | 0001 | 1 |
| | Bitwise OR | A | B | 0111 | 7 |
^ | Bitwise XOR | A ^ B | 0110 | 6 |
~ | Bitwise NOT | ~A | …11111010 | -6 |
<< | Left Shift | A << 1 | 1010 | 10 |
>> | Sign-propagating Right Shift | A >> 1 | 0010 | 2 |
>>> | Zero-fill Right Shift | A >>> 1 | 0010 | 2 |
String Operators
Section titled “String Operators”Concatenation Operator (+)
Section titled “Concatenation Operator (+)”Joins two strings together.
let firstName = "Jane";let lastName = "Doe";let fullName = firstName + " " + lastName; // "Jane Doe"console.log(fullName);While + works, Template Literals (backticks `) are the modern and more readable way to embed expressions within strings:
let city = "Paris";let population = 2.1;let description = `The city of ${city} has a population of ${population} million.`;console.log(description);Conditional (Ternary) Operator (? :)
Section titled “Conditional (Ternary) Operator (? :)”A shorthand for simple if...else statements. condition ? value_if_true : value_if_false
let userAge = 20;let canVote = userAge >= 18 ? "Yes" : "No"; // canVote will be "Yes"console.log(`Can vote? ${canVote}`);Type Operators
Section titled “Type Operators”| Operator | Description | Example |
|---|---|---|
typeof | Returns a string indicating the type of the unevaluated operand. | typeof 42 returns 'number', typeof 'hello' returns 'string' |
instanceof | Checks if an object is an instance of a particular class or constructor. | myDate instanceof Date returns true if myDate was created with new Date() |
Modern Operators (ES2020+)
Section titled “Modern Operators (ES2020+)”Optional Chaining (?.)
Section titled “Optional Chaining (?.)”Safely access properties of an object that might be null or undefined without causing an error. If any part of the chain before ?. is null or undefined, the expression short-circuits and returns undefined.
interface User { name: string; address?: { street?: string; city: string; };}
const user1: User = { name: "Alice", address: { city: "London" } };const user2: User = { name: "Bob" };
const street1 = user1.address?.street; // Access safely -> undefined (street doesn't exist)const street2 = user2.address?.street; // Access safely -> undefined (address doesn't exist)// const street3 = user2.address.street; // This would cause a runtime error!
console.log(`User 1 Street: ${street1}`);console.log(`User 2 Street: ${street2}`);Nullish Coalescing Operator (??)
Section titled “Nullish Coalescing Operator (??)”Provides a default value when an expression is null or undefined. Unlike || (logical OR), it only triggers for null or undefined, not for other falsy values like 0, '', or false.
let volume: number | null | undefined = 0;let configVolume = volume ?? 100; // configVolume is 0 (because 0 is not null/undefined)
let userSetting: string | null = null;let defaultSetting = "Default";let activeSetting = userSetting ?? defaultSetting; // activeSetting is "Default"
// Compare with ||let oldConfigVolume = volume || 100; // oldConfigVolume is 100 (because 0 is falsy)
console.log(`Config Volume (??): ${configVolume}`);console.log(`Active Setting (??): ${activeSetting}`);console.log(`Old Config Volume (||): ${oldConfigVolume}`);