Skip to content

TypeScript - Operators

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; // 8

Here, 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

Perform standard mathematical calculations. Assume let a = 10; let b = 4;

OperatorDescriptionExampleResult
+Additiona + b14
-Subtractiona - b6
*Multiplicationa * b40
/Divisiona / b2.5
%Modulus (Remainder)a % b2
**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

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.

OperatorDescriptionExampleResult
>Greater thanz > xtrue
<Less thanx < ztrue
>=Greater than or equal tox >= 5true
<=Less than or equal toz <= 5false
===Strict Equality (value and type)x === 5true
===Strict Equalityx === yfalse (number vs string)
!==Strict Inequality (value or type)x !== ytrue
==Loose Equality (value, after type coercion)x == ytrue (string ‘5’ coerced to number 5)
!=Loose Inequalityx != 5false

Combine boolean expressions. Assume let p = true; let q = false;

OperatorDescriptionExampleResult
&&Logical AND (true if both operands are true)p && qfalse
||Logical OR (true if at least one operand is true)p || qtrue
!Logical NOT (inverts boolean value)!pfalse

Logical operators use short-circuiting: && stops evaluating if the first operand is false, || stops if the first is true.

Assign values to variables.

OperatorExampleEquivalent 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;

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);

OperatorDescriptionExampleResult (Binary)Result (Decimal)
&Bitwise ANDA & B00011
|Bitwise ORA | B01117
^Bitwise XORA ^ B01106
~Bitwise NOT~A…11111010-6
<<Left ShiftA << 1101010
>>Sign-propagating Right ShiftA >> 100102
>>>Zero-fill Right ShiftA >>> 100102

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);

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}`);
OperatorDescriptionExample
typeofReturns a string indicating the type of the unevaluated operand.typeof 42 returns 'number', typeof 'hello' returns 'string'
instanceofChecks if an object is an instance of a particular class or constructor.myDate instanceof Date returns true if myDate was created with new Date()

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}`);

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}`);