JavaScript Arithmetic
JavaScript, as a versatile and widely-used programming language, provides a robust set of arithmetic operators to perform various mathematical operations. In this article, we will delve into the fundamentals of JavaScript arithmetic, exploring essential operators and providing illustrative examples to enhance your understanding.
Addition Operator (+):
The addition operator in JavaScript is represented by the plus sign (+). It is used to add two or more values together.
Example:
let sum = 5 + 3;
console.log("Sum:", sum); // Output: Sum: 8
Subtraction Operator (-):
The subtraction operator, denoted by the minus sign (-), subtracts the right operand from the left operand.
Example:
let difference = 10 - 4;
console.log("Difference:", difference); // Output: Difference: 6
Multiplication Operator (*):
The multiplication operator (*), as expected, multiplies two or more values.
Example:
let product = 6 * 7;
console.log("Product:", product); // Output: Product: 42
Division Operator (/):
The division operator (/) divides the left operand by the right operand.
Example:
let quotient = 15 / 3;
console.log("Quotient:", quotient); // Output: Quotient: 5
Modulus Operator (%):
The modulus operator (%) returns the remainder of the division of the left operand by the right operand.
Example:
let remainder = 17 % 5;
console.log("Remainder:", remainder); // Output: Remainder: 2
Increment (++) and Decrement (–) Operators:
The increment (++) and decrement (–) operators add or subtract 1 from a variable, respectively.
Example:
let x = 10;
x++;
console.log("Incremented:", x); // Output: Incremented: 11
let y = 8;
y--;
console.log("Decremented:", y); // Output: Decremented: 7
Conclusion:
JavaScript’s arithmetic operators play a crucial role in performing mathematical calculations within your code. Whether you’re building a simple calculator or manipulating data, a solid understanding of these operators is essential. By applying the examples provided, you’ll be better equipped to leverage JavaScript’s arithmetic capabilities in your programming endeavors.