JavaScript provides several arithmetic operators:
+
): Used to add two or more numbers. It can also be used to concatenate strings.-
): Subtracts the right - hand operand from the left - hand operand.*
): Multiplies two numbers./
): Divides the left - hand operand by the right - hand operand.%
): Returns the remainder of the division of the left - hand operand by the right - hand operand.**
): Raises the left - hand operand to the power of the right - hand operand.An arithmetic expression is a combination of values, variables, and operators that evaluates to a single value. For example, 2 + 3
is an arithmetic expression that evaluates to 5
.
// Adding numbers
let num1 = 5;
let num2 = 3;
let sum = num1 + num2;
console.log(sum); // Output: 8
// Concatenating strings
let str1 = "Hello";
let str2 = " World";
let combinedStr = str1 + str2;
console.log(combinedStr); // Output: Hello World
let num3 = 10;
let num4 = 4;
let difference = num3 - num4;
console.log(difference); // Output: 6
let num5 = 6;
let num6 = 7;
let product = num5 * num6;
console.log(product); // Output: 42
let num7 = 15;
let num8 = 3;
let quotient = num7 / num8;
console.log(quotient); // Output: 5
let num9 = 17;
let num10 = 5;
let remainder = num9 % num10;
console.log(remainder); // Output: 2
let base = 2;
let exponent = 3;
let result = base ** exponent;
console.log(result); // Output: 8
let scores = [80, 90, 75, 85];
let sumOfScores = 0;
for (let i = 0; i < scores.length; i++) {
sumOfScores += scores[i];
}
let average = sumOfScores / scores.length;
console.log(average);
let counter = 0;
counter++; // Increment the counter by 1
console.log(counter); // Output: 1
When dealing with complex expressions, use parentheses to make the order of operations clear.
// Without parentheses
let result1 = 2 + 3 * 4; // Multiplication first, then addition. Result: 14
// With parentheses
let result2 = (2 + 3) * 4; // Addition first, then multiplication. Result: 20
When performing division operations, always check if the divisor is zero to avoid runtime errors.
let numerator = 10;
let denominator = 0;
if (denominator!== 0) {
let quotient = numerator / denominator;
console.log(quotient);
} else {
console.log("Cannot divide by zero");
}
Arithmetic operators and expressions in JavaScript are powerful tools that enable developers to perform a wide variety of mathematical operations. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can write more efficient and error - free code. Whether you are working on simple web applications or complex algorithms, a solid grasp of arithmetic in JavaScript is essential.