JavaScript Function to Calculate the Sum of Two Numbers

Introduction

Adding two numbers is one of the most basic operations in programming. This task is often used as a simple demonstration of how functions work. This program will demonstrate how to create a JavaScript function that accepts two numbers, calculates their sum, and returns the result.

Problem Statement

Create a JavaScript function that:

  • Accepts two numbers as arguments.
  • Calculates the sum of the two numbers.
  • Returns and displays the result.

Example:

  • Input: 5, 7

  • Output: 12

  • Input: 10, 20

  • Output: 30

Solution Steps

  1. Create a Function: Define a function that accepts two parameters.
  2. Calculate the Sum: Add the two parameters inside the function.
  3. Return the Result: Return the calculated sum.
  4. Display the Result: Print the sum of the two numbers.

JavaScript Program

// JavaScript Function to Calculate the Sum of Two Numbers
// Author: https://www.javaguides.net/

function sumTwoNumbers(num1, num2) {
    // Step 1: Calculate the sum of the two numbers
    let sum = num1 + num2;

    // Step 2: Return the result
    return sum;
}

// Example input
let number1 = 5;
let number2 = 7;
let result = sumTwoNumbers(number1, number2);
console.log(`The sum of ${number1} and ${number2} is: ${result}`);

Output

The sum of 5 and 7 is: 12

Example with Different Input

let number1 = 10;
let number2 = 20;
let result = sumTwoNumbers(number1, number2);
console.log(`The sum of ${number1} and ${number2} is: ${result}`);

Output:

The sum of 10 and 20 is: 30

Explanation

Step 1: Create a Function

  • The function sumTwoNumbers() is defined with two parameters, num1 and num2, which represent the two numbers to be summed.

Step 2: Calculate the Sum

  • Inside the function, the sum of num1 and num2 is calculated using the + operator.

Step 3: Return and Display the Result

  • The result of the addition is returned by the function and printed using console.log().

Conclusion

This JavaScript function demonstrates how to calculate the sum of two numbers by defining a simple function with parameters. This solution is basic yet fundamental and can be extended to more complex mathematical operations or integrated into larger applications.

Comments