Arithmetic Operators in JavaScript

Arithmetic operators in JavaScript are used when we need to perform arithmetical task. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      let x = 10, y = 20;
      document.write(x, "+", y, " = ", x+y);
   </script>
   
</body>
</html>
Output

List of All Arithmetic Operators in JavaScript

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Exponentiation (**)
  • Division (/)
  • Modulus (%)
  • Increment (++)
  • Decrement (--)

JavaScript Arithmetic Operators Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      let a = 20, b = 10, c = 3, d = 4;

      res = a+b;
      document.write(res, "<BR>");
      
      res = a-b;
      document.write(res, "<BR>");
      
      res = a*b;
      document.write(res, "<BR>");
      
      res = c**d;
      document.write(res, "<BR>");
      
      res = a/b;
      document.write(res, "<BR>");
      
      res = a%c;
      document.write(res, "<BR>");
      
      res = a++;
      document.write(res, "<BR>");
      
      res = a--;
      document.write(res, "<BR>");
   </script>
   
</body>
</html>
Output

Increment/Decrement Operator in JavaScript

Both increment and decrement operators in JavaScript are of two types, that are:

  • Pre-increment operator (++x)
  • Post-increment operator (x++)
  • Pre-decrement operator (--x)
  • Post-decrement operator (x--)

The pre-increment/decrement is used to increment/decrement the value before use. Whereas the post-increment/decrement is used to use the value before increment/decrement. The value will be incremented/decremented by 1 each time. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      let m = 10, n = 20;

      document.write(m++);
      document.write("<BR>");
      document.write(m);
      document.write("<BR>");
      
      document.write(++m);
      document.write("<BR>");
      document.write(m);
      document.write("<BR>");

      document.write(n--);
      document.write("<BR>");
      document.write(n);
      document.write("<BR>");
      
      document.write(--n);
      document.write("<BR>");
      document.write(n);
      document.write("<BR>");
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »