A Comprehensive Guide to JavaScript Arithmetic Operators
A Comprehensive Guide to JavaScript Arithmetic Operators
JavaScript provides a variety of arithmetic operators that enable developers to perform essential mathematical operations on numbers. This guide breaks down the primary arithmetic operators and their usage, ensuring a clear understanding for effective coding.
Key Arithmetic Operators
- Addition (
+
)- Description: Adds two numbers.
- Example:
let sum = 5 + 3; // sum is 8
- Subtraction (
-
)- Description: Subtracts one number from another.
- Example:
let difference = 10 - 4; // difference is 6
- Multiplication (
*
)- Description: Multiplies two numbers.
- Example:
let product = 7 * 6; // product is 42
- Division (
/
)- Description: Divides one number by another.
- Example:
let quotient = 20 / 4; // quotient is 5
- Modulus (
%
)- Description: Returns the remainder of a division operation.
- Example:
let remainder = 10 % 3; // remainder is 1
- Exponentiation (
**
)- Description: Raises a number to the power of another number.
- Example:
let power = 2 ** 3; // power is 8 (2 to the power of 3)
Important Notes
- Operator Precedence: Arithmetic operators follow a specific order of operations similar to standard mathematics, where multiplication and division are prioritized over addition and subtraction.
- NaN (Not a Number): Performing operations that yield an invalid number results in `NaN` in JavaScript.
- Example:
let invalidOperation = "Hello" - 5; // invalidOperation is NaN
- Example:
Conclusion
Understanding these fundamental arithmetic operators is crucial for executing calculations in JavaScript. Developers can combine these operators in expressions to create complex calculations while adhering to the established order of operations.