JavaScript Program to Subtract Two Numbers

Introduction

Subtracting two numbers is a basic arithmetic operation commonly used in programming. In JavaScript, you can easily perform subtraction using the - operator. This guide will walk you through writing a JavaScript program to subtract two numbers.

Problem Statement

Create a JavaScript program that:

  • Accepts two numbers.
  • Subtracts the second number from the first number.
  • Returns the result of the subtraction.

Example:

  • Input: 15 and 5

  • Output: 10

  • Input: 7 and 3

  • Output: 4

Solution Steps

  1. Read the Input Numbers: Provide two numbers either as part of user input or directly in the code.
  2. Subtract the Numbers: Use the - operator to subtract the second number from the first.
  3. Display the Result: Print the result of the subtraction.

JavaScript Program

// JavaScript Program to Subtract Two Numbers
// Author: https://www.javaguides.net/

function subtractTwoNumbers(num1, num2) {
    // Step 1: Subtract the second number from the first
    const difference = num1 - num2;
    
    // Step 2: Display the result
    console.log(`The difference between ${num1} and ${num2} is: ${difference}`);
}

// Example input
let number1 = 15;
let number2 = 5;
subtractTwoNumbers(number1, number2);

Output Example

The difference between 15 and 5 is: 10

Example with Different Input

If you modify the input to:

let number1 = 7;
let number2 = 3;

The output will be:

The difference between 7 and 3 is: 4

Explanation

Step 1: Subtract the Two Numbers

  • The numbers are passed as arguments to the subtractTwoNumbers() function, where they are subtracted using the - operator.

Step 2: Display the Result

  • The result of the subtraction is stored in the variable difference and displayed using console.log().

Conclusion

This JavaScript program demonstrates how to subtract two numbers using the - operator. This basic arithmetic operation is essential in many programming tasks, and the program serves as a foundation for learning how to perform mathematical operations in JavaScript.

Comments