JavaScript provides a robust set of arithmetic operators to perform mathematical calculations. These operators are fundamental for numerical operations, allowing you to add, subtract, multiply, divide, find the remainder, and perform exponentiation.
Example 1: Addition Operator (+)
// Example 1: Adding two numbers
let firstNumber = 15;
let secondNumber = 10;
let sum = firstNumber + secondNumber; // The addition operator (+) adds the two numbers
console.log(sum); // Output: 25
Explanation
In this example, the addition operator +
is used to add the values of firstNumber
and secondNumber
. The result of this operation is then stored in the sum
variable.
Example 2: String Concatenation with the Addition Operator (+)
// Example 2: Concatenating strings
let greeting = "Hello, ";
let name = "Alice";
let message = greeting + name; // The addition operator (+) concatenates the two strings
console.log(message); // Output: "Hello, Alice"
Explanation
The addition operator +
can also be used for string concatenation. When used with strings, it joins them together to create a new string, as shown above where greeting
and name
are combined.
Example 3: Adding a Number and a String
// Example 3: Adding a number and a string
let apples = 5;
let announcement = "I have " + apples + " apples."; // JavaScript converts the number to a string for concatenation
console.log(announcement); // Output: "I have 5 apples."
Explanation
When the addition operator +
is used with a number and a string, JavaScript converts the number to a string and then concatenates the two. This is a process known as type coercion.
Example 1: Subtraction Operator (-)
// Example 1: Subtracting two numbers
let totalAmount = 200;
let discount = 50;
let finalAmount = totalAmount - discount; // The subtraction operator (-) subtracts the discount from the total amount
console.log(finalAmount); // Output: 150
Explanation
This code demonstrates the basic use of the subtraction operator -
. It calculates the difference between totalAmount
and discount
and stores the result in finalAmount
.
Example 2: Subtracting from a Negative Number
// Example 2: Subtracting from a negative number
let initialTemperature = -10;
let temperatureDrop = 5;
let newTemperature = initialTemperature - temperatureDrop; // Subtracting a positive number from a negative number
console.log(newTemperature); // Output: -15
Explanation
Here, the subtraction operator -
is used to subtract temperatureDrop
from a negative initialTemperature
. This results in a more negative number.
Example 3: Unary Negation with the Subtraction Operator (-)
// Example 3: Using the subtraction operator for unary negation
let positiveNumber = 25;
let negativeNumber = -positiveNumber; // The subtraction operator (-) is used to negate the value
console.log(negativeNumber); // Output: -25
Explanation
The subtraction operator -
can also function as a unary operator to negate a value. In this case, it changes the sign of positiveNumber
from positive to negative.
Example 1: Multiplication Operator (*)
// Example 1: Multiplying two numbers
let pricePerItem = 25;
let numberOfItems = 4;
let totalCost = pricePerItem * numberOfItems; // The multiplication operator (*) calculates the total cost
console.log(totalCost); // Output: 100
Explanation
The multiplication operator *
is used here to find the product of pricePerItem
and numberOfItems
. The result is the totalCost
of the purchase.
Example 2: Multiplying with a Floating-Point Number
// Example 2: Multiplying with a floating-point number
let distance = 7.5;
let speed = 60;
let timeTaken = distance * speed; // Multiplying a floating-point number with an integer
console.log(timeTaken); // Output: 450
Explanation
This example shows the multiplication of a floating-point number (distance
) with an integer (speed
). JavaScript handles these calculations seamlessly.
Example 3: Multiplying with a Negative Number
// Example 3: Multiplying with a negative number
let profitPerUnit = 50;
let returnedUnits = -3;
let totalProfitLoss = profitPerUnit * returnedUnits; // Calculating the loss from returned units
console.log(totalProfitLoss); // Output: -150
Explanation
When multiplying a positive number by a negative number, the result is negative. The *
operator correctly calculates the totalProfitLoss
as a negative value.
Example 1: Division Operator (/)
// Example 1: Dividing two numbers
let totalSlices = 12;
let numberOfPeople = 4;
let slicesPerPerson = totalSlices / numberOfPeople; // The division operator (/) divides the total slices by the number of people
console.log(slicesPerPerson); // Output: 3
Explanation
The division operator /
is used to divide totalSlices
by numberOfPeople
, resulting in the number of slicesPerPerson
.
Example 2: Division Resulting in a Floating-Point Number
// Example 2: Division resulting in a floating-point number
let totalDistance = 100;
let time = 8;
let averageSpeed = totalDistance / time; // Division that results in a decimal value
console.log(averageSpeed); // Output: 12.5
Explanation
In this case, the division of totalDistance
by time
does not result in a whole number. JavaScript's /
operator handles this by returning a floating-point number.
Example 3: Division by Zero
// Example 3: Division by zero
let numerator = 15;
let denominator = 0;
let result = numerator / denominator; // Dividing a number by zero
console.log(result); // Output: Infinity
Explanation
When a number is divided by zero in JavaScript, the result is Infinity
. This is a special numeric value representing an infinitely large number.
Example 1: Modulo Operator (%)
// Example 1: Finding the remainder of a division
let totalItems = 17;
let itemsPerBox = 5;
let leftoverItems = totalItems % itemsPerBox; // The modulo operator (%) finds the remainder
console.log(leftoverItems); // Output: 2
Explanation
The modulo operator %
returns the remainder of a division operation. Here, it calculates how many leftoverItems
there are after packing totalItems
into boxes that hold itemsPerBox
.
Example 2: Checking for Even or Odd Numbers
// Example 2: Checking if a number is even or odd
let numberToCheck = 20;
let remainder = numberToCheck % 2; // If the remainder is 0, the number is even
console.log(remainder); // Output: 0
Explanation
A common use of the modulo operator %
is to determine if a number is even or odd. If a number divided by 2 has a remainder of 0, it is even.
Example 3: Using Modulo with Floating-Point Numbers
// Example 3: Modulo with floating-point numbers
let dividend = 7.5;
let divisor = 2.2;
let floatRemainder = dividend % divisor; // Finding the remainder with floating-point numbers
console.log(floatRemainder); // Output: 0.9000000000000004
Explanation
The modulo operator %
can also be used with floating-point numbers. It returns the remainder of the division, though be mindful of potential floating-point inaccuracies.
Example 1: Exponentiation Operator (**)
// Example 1: Squaring a number
let sideLength = 6;
let area = sideLength ** 2; // The exponentiation operator (**) raises sideLength to the power of 2
console.log(area); // Output: 36
Explanation
The exponentiation operator **
raises the left operand to the power of the right operand. In this example, it calculates the square of sideLength
.
Example 2: Cubing a Number
// Example 2: Cubing a number
let numberToCube = 3;
let cubedResult = numberToCube ** 3; // Raising a number to the power of 3
console.log(cubedResult); // Output: 27
Explanation
Here, the exponentiation operator **
is used to cube numberToCube
by raising it to the power of 3.
Example 3: Finding the Root of a Number
// Example 3: Finding the square root of a number
let numberToRoot = 81;
let squareRoot = numberToRoot ** 0.5; // Raising a number to the power of 0.5 gives the square root
console.log(squareRoot); // Output: 9
Explanation
The exponentiation operator **
can also be used to find the roots of a number. Raising a number to the power of 0.5 is equivalent to calculating its square root.