TypeScript, a superset of JavaScript, brings static typing to the dynamic world of web development. While JavaScript itself is versatile, TypeScript enhances it by introducing strong typing, enabling developers to catch errors at compile-time rather than runtime. In this article, we’ll explore TypeScript’s arithmetic operators, their functionalities and provide code examples to solidify your understanding.
What Are Arithmetic Operators?
Arithmetic operators are symbols that perform mathematical operations on numeric operands. The operands can be variables, constants, or literal values. These operators are similar to those in JavaScript, providing developers with familiar tools for working with numbers. Let’s dive into each arithmetic operator and see how they can be applied in TypeScript.
Addition Operator (+)
The addition operator in TypeScript, denoted by the symbol ‘+’, adds two numeric values. Here’s an example:
let num1: number = 5;
let num2: number = 10;
let sum: number = num1 + num2;
console.log(`Sum: ${sum}`);
In this example, the variables num1 and num2 store numeric values, and the + operator is used to add them together. The result is stored in the variable sum and then printed to the console.
Subtraction Operator (-)
The subtraction operator (-) subtracts the right operand from the left operand. Here’s an example:
let initialBalance: number = 1000;
let withdrawalAmount: number = 200;
let remainingBalance: number = initialBalance - withdrawalAmount;
console.log(Remaining Balance: ${remainingBalance});
In this example, the initialBalance is decreased by the withdrawalAmount using the subtraction operator, resulting in the updated remainingBalance.
Multiplication Operator (*)
The multiplication operator (*) is used to multiply two numeric values. Let’s consider a scenario where we calculate the total cost of items:
let pricePerItem: number = 25;
let numberOfItems: number = 4;
let totalCost: number = pricePerItem * numberOfItems;
console.log(Total Cost: ${totalCost});
Here, the pricePerItem is multiplied by the numberOfItems to obtain the total cost of the items.
Division Operator (/)
The division operator (/) divides the left operand by the right operand. Suppose we want to calculate the average score of a student based on total marks and the number of subjects:
let totalMarks: number = 480;
let numberOfSubjects: number = 6;
let averageScore: number = totalMarks / numberOfSubjects;
console.log(Average Score: ${averageScore});
In this example, the totalMarks are divided by the numberOfSubjects to calculate the average score.
Be cautious with division, as dividing by zero will result in Infinity:
let infinityResult: number = 10 / 0;
console.log(infinityResult); // Output: Infinity
Modulus Operator (%)
The modulus operator (%) returns the remainder when the left operand is divided by the right operand. This is useful in scenarios like checking whether a number is even or odd:
let someNumber: number = 15;
if (someNumber % 2 === 0) {
console.log(${someNumber} is an even number.);
} else {
console.log(${someNumber} is an odd number.);
}
In this example, the modulus operator is used to determine whether someNumber is even or odd based on the remainder when divided by 2.
Exponentiation Operator (**)
The Exponentiation Operator (**), represented by two asterisks, is used to raise the left operand to the power of the right operand. This operator simplifies the process of calculating exponentials and makes code more concise.
let result = 2 ** 3; // 2 raised to the power of 3
console.log(result); // Output: 8
In this example, 2 ** 3 results in 2 raised to the power of 3, yielding 8. It’s a concise and readable way to express exponentiation.
Operator Precedence
Basic understanding of operator precedence is essential when combining multiple operators in an expression. TypeScript, like many programming languages, follows a set of rules to determine the order in which operators are evaluated.
Parentheses can be used to override the default precedence and explicitly define the order of evaluation.
let result: number = (5 + 3) * 2;
console.log(result); // Output: 16
In this example, the addition inside the parentheses is performed first, and then the multiplication is applied. Without the parentheses, multiplication would have taken precedence over the addition, resulting in 11. It’s advisable to always use parentheses to clarify your intent, and to avoid errors.
Below is a brief overview of TypeScript’s operator precedence from highest to lowest:
- Parentheses: ( )
- Exponentiation: **
- Multiplication, Division, Modulus: * / %
- Addition and Subtraction: + –
Operators with higher precedence are evaluated before those with lower precedence. If operators have the same precedence, the associativity (left-to-right or right-to-left) comes into play.
JavaScript Arithmetic Operators
For further information, kindly refer to the JavaScript Arithmetic Operators. Everything discussed on that page is also applicable in the context of TypeScript.
Conclusion
In this article, we’ve explored the various TypeScript arithmetic operators, ranging from the basic addition and subtraction to more advanced operations like exponentiation. Understanding these operators is fundamental to performing mathematical calculations in TypeScript and enhances your ability to write efficient and concise code.