JavaScript Arithmetic
Arithmetic operators in JavaScript are used to perform mathematical operations like addition, subtraction, multiplication, and division. These operators form the foundation for numerical calculations in JavaScript.
Key Topics
- Basic Arithmetic Operators
- Increment and Decrement Operators
- Modulus Operator
- Exponentiation Operator
- JavaScript Usage in DOM
- Key Takeaways
Basic Arithmetic Operators
The basic arithmetic operators are + (addition), - (subtraction), * (multiplication), and / (division).
let a = 15;
let b = 5;
console.log("Addition: ", a + b);
console.log("Subtraction: ", a - b);
console.log("Multiplication: ", a * b);
console.log("Division: ", a / b);
Output
> Addition: 20
> Subtraction: 10
> Multiplication: 75
> Division: 3
Explanation: The code demonstrates basic arithmetic operations using variables a and b. Each operation is performed and logged to the console.
Increment and Decrement Operators
The increment (++) and decrement (--) operators are used to increase or decrease a variable's value by 1.
let x = 10;
x++;
console.log("Incremented: ", x);
x--;
console.log("Decremented: ", x);
Output
> Incremented: 11
> Decremented: 10
Explanation: The variable x is incremented by 1 using ++ and decremented by 1 using --. The updated values are logged to the console.
Modulus Operator
The modulus operator (%) returns the remainder of a division operation.
let a = 17;
let b = 5;
console.log("Remainder: ", a % b);
Output
> Remainder: 2
Explanation: The code calculates the remainder of a divided by b using the modulus operator %. The result is logged to the console.
Exponentiation Operator
The exponentiation operator (**) calculates the power of a number.
let base = 3;
let exponent = 4;
console.log("Power: ", base ** exponent);
Output
> Power: 81
Explanation: The code calculates 3 raised to the power of 4 using the exponentiation operator **. The result is logged to the console.
JavaScript Usage in DOM
Below is a DOM-based example demonstrating arithmetic operators to calculate and display results dynamically in a browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arithmetic in DOM</title>
</head>
<body>
<h1>Arithmetic Operations</h1>
<p>Click the button to see the result:</p>
<button onclick="performArithmetic()">Calculate</button>
<p id="result"></p>
<script>
function performArithmetic() {
let a = 20;
let b = 4;
let sum = a + b;
document.getElementById("result").textContent = "Sum: " + sum;
}
</script>
</body>
</html>
Key Takeaways
- Basic Arithmetic: Operators like
+,-,*, and/are essential for calculations. - Increment and Decrement: Use
++and--for single-step adjustments. - Modulus: Returns the remainder of division operations.
- Exponentiation: The
**operator calculates powers. - Dynamic Usage: Apply arithmetic in DOM manipulations to make content interactive.