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>

  <p>10 + 20 = <span id="mySpan"></span></p>
   
   <script>
      let x = 10, y = 20;
      document.getElementById("mySpan").innerHTML = x+y;
   </script>
   
</body>
</html>
Output

10 + 20 =

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>
   
   <p id="1"></p>
   <p id="2"></p>
   <p id="3"></p>
   <p id="4"></p>
   <p id="5"></p>
   <p id="6"></p>
   <p id="7"></p>
   <p id="8"></p>
   
   <script>
      let a = 20, b = 10, c = 3, d = 4;

      res = a+b;
      document.getElementById("1").innerHTML = res;
      
      res = a-b;
      document.getElementById("2").innerHTML = res;
      
      res = a*b;
      document.getElementById("3").innerHTML = res;
      
      res = c**d;
      document.getElementById("4").innerHTML = res;
      
      res = a/b;
      document.getElementById("5").innerHTML = res;
      
      res = a%c;
      document.getElementById("6").innerHTML = res;
      
      res = a++;
      document.getElementById("7").innerHTML = res;
      
      res = a--;
      document.getElementById("8").innerHTML = res;
   </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>
   
   <p id="a"></p> 
   <p id="b"></p> 
   <p id="c"></p> 
   <p id="d"></p> 
   <p id="e"></p> 
   <p id="f"></p> 
   <p id="g"></p> 
   <p id="h"></p> 

   <script>
      let m = 10, n = 20;

      document.getElementById("a").innerHTML = m++;
      document.getElementById("b").innerHTML = m;
      
      document.getElementById("c").innerHTML = ++m;
      document.getElementById("d").innerHTML = m;
        
      document.getElementById("e").innerHTML = n--;
      document.getElementById("f").innerHTML = n;
      
      document.getElementById("g").innerHTML = --n;
      document.getElementById("h").innerHTML = n;
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube