Arithmetic operators are used to perform mathematical operations on variables or values.
let x: number = 10;
let y: number = 5;
let sum: number = x + y; ## sum will be 15
Description: The addition operator (+) adds two operands.
Explanation: In this example, x
is assigned the value 10
, y
is assigned the value 5
, and sum
is assigned the sum of x
and y
, which is 15
.
let difference: number = x - y; ## difference will be 5
Description: The subtraction operator (-) subtracts the right operand from the left operand.
Explanation: In this example, difference
is assigned the difference of x
and y
, which is 5
.
let product: number = x * y; ## product will be 50
Description: The multiplication operator (*) multiplies two operands.
Explanation: In this example, product
is assigned the product of x
and y
, which is 50
.
let quotient: number = x / y; ## quotient will be 2
Description: The division operator (/) divides the left operand by the right operand.
Explanation: In this example, quotient
is assigned the quotient of dividing x
by y
, which is 2
.
let remainder: number = x % y; ## remainder will be 0
Description: The modulus operator (%) returns the remainder of dividing the left operand by the right operand.
Explanation: In this example, remainder
is assigned the remainder of dividing x
by y
, which is 0
.
let power: number = x ** 2; ## power will be 100 (10 raised to the power of 2)
Description: The exponentiation operator (**) raises the left operand to the power of the right operand.
Explanation: In this example, power
is assigned the result of raising x
to the power of 2
, which is 100
.
let num: number = 5;
num++; ## num will be 6
Description: The increment operator (++) increases the value of the operand by 1.
Explanation: In this example, num
is incremented by 1, so its value becomes 6
.
num--; ## num will be 5 again
Description: The decrement operator (--) decreases the value of the operand by 1.
Explanation: In this example, num
is decremented by 1, so its value returns to 5
.
- Arithmetic operators in TypeScript perform common mathematical operations such as addition, subtraction, multiplication, division, modulus, exponentiation, increment, and decrement.
- These operators can be applied to variables of numeric types, such as number or bigint, to perform mathematical calculations.
- Understanding arithmetic operators is fundamental for performing calculations and manipulating numeric data in TypeScript programs.