TypeScript - Arithmetic Operators Examples

Assume the values in variables a and b are 10 and 5 respectively.

Operator Description Example
+ (Addition) returns the sum of the operands a + b is 15
- (Subtraction) returns the difference of the values a - b is 5
* (Multiplication) returns the product of the values a * b is 50
/ (Division) performs a division operation and returns the quotient a / b is 2
% (Modulus) performs a division and returns the remainder a % b is 0
++ (Increment) Increments the value of the variable by one a++ is 11
-- (Decrement) Decrements the value of the variable by one a-- is 9

Example

var num1:number = 10
var num2:number = 2
var res:number = 0

res = num1 + num2
console.log("Sum:        "+res);

res = num1 - num2;
console.log("Difference: "+res)

res = num1*num2
console.log("Product:    "+res)

res = num1/num2
console.log("Quotient:   "+res)

res = num1%num2
console.log("Remainder:   "+res)

num1++
console.log("Value of num1 after increment "+num1)

num2--
console.log("Value of num2 after decrement "+num2)

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10
var num1 = 10;
var num2 = 2;
var res = 0;

res = num1 + num2;
console.log("Sum:        " + res);

res = num1 - num2;
console.log("Difference: " + res);

res = num1 * num2;
console.log("Product:    " + res);

res = num1 / num2;
console.log("Quotient:   " + res);

res = num1 % num2;
console.log("Remainder:   " + res);

num1++;
console.log("Value of num1 after increment " + num1);

num2--;
console.log("Value of num2 after decrement " + num2);

The output of the above program is given below −

Sum: 12
Difference: 8
Product: 20
Quotient : 5
Remainder: 0
Value of num1 after increment: 11
Value of num2 after decrement: 1
typescript_operators.htm

Useful Video Courses

Video

Angular Essentials - Admin App, Typescript, Docker, c3.js

45 Lectures 4 hours

Video

NestJs: Modern ways to build APIs with Typescript and NestJs

41 Lectures 7 hours

Video

Master Typescript : Learn Typescript from scratch

60 Lectures 2.5 hours

Video

Three.js and TypeScript

77 Lectures 8 hours

Video

TypeScript from Scratch: Go from zero to hero in TypeScript

77 Lectures 3.5 hours

Video

Advanced TypeScript: Generic Search, Sorting and Filtering

19 Lectures 3 hours