JavaScript Program to Add Two Numbers

Introduction

Adding two numbers is one of the simplest and most common operations in programming. This task can be easily accomplished in JavaScript using different approaches. This guide will walk you through writing a JavaScript program to add two numbers.

Problem Statement

Create a JavaScript program that:

  • Accepts two numbers.
  • Adds the two numbers.
  • Returns the sum.

Example:

  • Input: 5 and 10

  • Output: 15

  • Input: 7 and 3

  • Output: 10

Solution Steps

  1. Read the Input Numbers: Provide two numbers either as part of user input or directly in the code.
  2. Add the Numbers: Use the + operator to sum the two numbers.
  3. Display the Result: Print the sum of the two numbers.

JavaScript Program

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

function addTwoNumbers(num1, num2) {
    // Step 1: Add the two numbers
    const sum = num1 + num2;
    
    // Step 2: Display the result
    console.log(`The sum of ${num1} and ${num2} is: ${sum}`);
}

// Example input
let number1 = 5;
let number2 = 10;
addTwoNumbers(number1, number2);

Output Example

The sum of 5 and 10 is: 15

Example with Different Input

If you modify the input to:

let number1 = 7;
let number2 = 3;

The output will be:

The sum of 7 and 3 is: 10

Explanation

Step 1: Add the Two Numbers

  • The numbers are passed as arguments to the addTwoNumbers() function, where they are added using the + operator.

Step 2: Display the Result

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

Conclusion

This JavaScript program demonstrates a simple way to add two numbers using the + operator. It is useful for learning basic arithmetic operations and how to handle input and output in JavaScript. This program can be extended to handle more complex arithmetic operations as needed.

Comments