JavaScript Arithmetic operators


Arithmetic operators in JavaScript are used to perform mathematical operations on numeric values. Here’s a closer look at each of them:

1. Addition (+)

  • Purpose: Adds two numbers or concatenates strings.
  • Example:
    let a = 5; let b = 3; let sum = a + b; // sum is 8
    let str1 = 'Hello'; let str2 = 'World'; let greeting = str1 + ' ' + str2; // greeting is 'Hello World'

2. Subtraction (-)

  • Purpose: Subtracts one number from another.
  • Example:
    let a = 10; let b = 4; let difference = a - b; // difference is 6

3. Multiplication (*)

  • Purpose: Multiplies two numbers.
  • Example:
    let a = 7; let b = 6; let product = a * b; // product is 42

4. Division (/)

  • Purpose: Divides one number by another.
  • Example:
    let a = 20; let b = 4; let quotient = a / b; // quotient is 5

5. Modulus (%)

  • Purpose: Returns the remainder of a division operation.
  • Example:
    let a = 10; let b = 3; let remainder = a % b; // remainder is 1

6. Exponentiation (**)

  • Purpose: Raises a number to the power of another number.
  • Example:
    let base = 2; let exponent = 3; let result = base ** exponent; // result is 8 (2^3)

Key Points:

  • Type Coercion: The + operator can also perform string concatenation if one of the operands is a string. For example, '5' + 1 results in '51' because JavaScript coerces the number 1 into a string.
  • Division by Zero: Dividing by zero does not throw an error in JavaScript; instead, it results in Infinity or -Infinity, depending on the sign of the numerator. For example, 10 / 0 results in Infinity.
  • NaN: The result of an arithmetic operation that doesn’t yield a valid number, such as 0 / 0 or Math.sqrt(-1), is NaN (Not-a-Number).