Mastering TypeScript Arithmetic and Logical Operations
Introduction to Arithmetic and Logical Operations
Welcome! Today, we will traverse the galaxy of TypeScript arithmetic and logical operations. Arithmetic operations, similar to basic mathematics, help us conduct simple calculations. Logical operations, on the contrary, assist us in evaluating conditions and making decisions. They act as game controllers, steering your character's next action based on the current circumstances.
Suppose you were in a toy store with only $20 at hand, and each toy was priced at $5. Most likely, you would perform a division operation to determine how many toys you could afford. But what if you wanted to buy a board game ($7) and a puzzle ($6) with your $20? Logical operations would then come into play, helping you make the right decision. Let's explore!
Getting Started with Arithmetic Operations
Arithmetic operations in TypeScript are simple and bear a strong resemblance to those in basic mathematics. We use + for addition, - for subtraction, * for multiplication, / for division, % for determining the remainder of a division, and ** for exponentiation.
As showcased in the example above, operators are inserted between two numbers to perform the calculations.
Integer Division in TypeScript
A common question is - how to perform integer division? If I have $21 and want to know how many $4 toys I can purchase, how can I calculate this? All numbers in TypeScript are floating point, but there is a way to identify the integer part of a number:
So, in essence, we use Math.floor to obtain the integer part (5) from the number 5.25, rounding it down.
Exploring the Power of Logical Operations
While arithmetic operations focus on numeric computations, logical operations deal with conditions. They yield a boolean value: true or false. TypeScript uses AND (&&), OR (||), and NOT (!) to perform logical operations.
In this instance, we used the actual boolean values — true and false — to illustrate the fundamental functioning of logical operators. However, in real coding scenarios, these true and false values would likely be expressions, such as (b > 5) && (b < 8).
