Arithmetic Operators in JavaScript

Arithmetic Operators in JavaScript

In Javascript, arithmetic operators are used to perform mathematical calculations. The numeric values in an arithmetic operator are called operands, while the arithmetic operation performed is called the operator.

The basic arithmetic operators in Javascript are:

  1. Addition Operator (+): The addition operator is used to add two or more operands.

     let x = 10
     let y = 2
    
     let result = x + y
     console.log(result)
     //result = 12 (10 plus 2)
    
  2. Subtraction Operator (-): The subtraction operator is used to subtract one operand from another.

     let x = 9
     let y = 3
    
     let result = x - y
     console.log(result)
     //result = 6 (9 minus 3)
    
  3. Multiplication Operator (*): The multiplication operator is used to multiply operands.

     let x = 5
     let y = 5
    
     let result = x * y
     console.log(result)
     //result = 25 (5 multiplied by 5)
    
  4. Division Operator (/): The division operator is used to divide one operand by another.

     let x = 16
     let y = 4
    
     let result = x / y
     console.log(result)
     //result = 4 (16 divided by 4)
    
  5. Modulus Operator (%): The modulus operator is used to get the remainder after dividing one operand by another.

     let x = 20
     let y = 6
    
     let result = x % y
     console.log(result)
     //result = 2 (The remainder after dividing 20 by 6)
    
  6. Exponentiation Operator (**): The exponentiation operator is used to raise the value of an operand to the power of another operand.

     let x = 5
     let y = 3
    
     let result = x ** y
     console.log(result)
     //result = 125 (5 raised to the power of 3)
    
  7. Increment Operator (++): The increment operator is used to increase an operand by 1

     let x = 4
     x++
    
     let result = x++
     console.log(result)
     //result = 5 (Increases by 1)
    
  8. Decrement Operator (--): The decrement operator is used to decrease an operand by 1

     let x = 7
     x--
    
     let result = x--
     console.log(result)
     //result = 6 (Decreases by 1)
    

    Order of Operations

    Javascript follows an arithmetic standard called PEMDAS

    1. Parentheses

    2. Exponents

    3. Multiplication and Division

    4. Addition and Subtraction

The PEMDAS rule makes it easier to remember the order of arithmetic operations. First, solve anything inside parentheses. Next, solve any exponents. After that, multiplication or division is performed as you move from left to right across the operation. Finally, finish with addition or subtraction, also from left to right.