What is Subtraction Operator (-) in JavaScript?

The subtraction operator (-) is a binary arithmetic operator in JavaScript that subtracts the right operand from the left operand. It requires two operands and returns the mathematical difference between them.

The subtraction operator follows standard mathematical rules - if the first operand is larger, the result is positive; if smaller, the result is negative.

Syntax

let result = operand1 - operand2;

Basic Examples

console.log(9 - 5);    // 4 (positive result)
console.log(5 - 9);    // -4 (negative result)
console.log(10 - 10);  // 0 (zero result)
console.log(3.5 - 1.2); // 2.3 (decimal numbers)
4
-4
0
2.3

Type Conversion with Subtraction

JavaScript automatically converts operands to numbers when using the subtraction operator:

console.log("10" - "3");   // 7 (strings converted to numbers)
console.log("15" - 5);     // 10 (string converted to number)
console.log(20 - "8");     // 12 (string converted to number)
console.log("abc" - 5);    // NaN (invalid conversion)
7
10
12
NaN

Interactive Example

<html>
   <body>
      <h2>JavaScript Subtraction Calculator</h2>
      <p>Enter two numbers:</p>
      <label>First Number:</label><input type="number" id="num1"><br><br>
      <label>Second Number:</label><input type="number" id="num2"><br><br>
      <button onclick="calculate()">Calculate Difference</button>
      <p id="result"></p>
      <script>
         function calculate() {
            var num1 = Number(document.getElementById("num1").value);
            var num2 = Number(document.getElementById("num2").value);
            var difference = num1 - num2;
            document.getElementById("result").innerHTML = 
               num1 + " - " + num2 + " = " + difference;
         }
      </script>
   </body>
</html>

Array Element Subtraction

You can use the subtraction operator to perform element-wise subtraction between arrays:

let array1 = [10, 15, 20, 25, 30];
let array2 = [3, 5, 8, 10, 12];
let result = [];

for (let i = 0; i < array1.length; i++) {
    result[i] = array1[i] - array2[i];
}

console.log("Array 1:", array1);
console.log("Array 2:", array2);
console.log("Difference:", result);
Array 1: [ 10, 15, 20, 25, 30 ]
Array 2: [ 3, 5, 8, 10, 12 ]
Difference: [ 7, 10, 12, 15, 18 ]

Common Use Cases

  • Age calculation: current year - birth year
  • Distance calculation: end point - start point
  • Price reduction: original price - discount
  • Time differences: end time - start time

Conclusion

The subtraction operator (-) is essential for mathematical calculations in JavaScript. It automatically converts operands to numbers and follows standard arithmetic rules for positive, negative, and zero results.

Updated on: 2026-03-15T22:00:29+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements