JavaScript Function: Sum of Two Numbers

1. Introduction

The basic arithmetic operation of addition is foundational in any programming language. In JavaScript, we can create a function to calculate the sum of two numbers with ease.

2. Program Overview

In this program, we will create a simple function named addNumbers that takes two parameters, adds them together, and returns the result.

3. Code Program

// Function to add two numbers
function addNumbers(a, b) {
    // Ensure both inputs are numbers
    if (typeof a !== 'number' || typeof b !== 'number') {
        return 'Both inputs should be numbers.';
    }

    // Return the sum of a and b
    return a + b;
}

// Test the function
let result1 = addNumbers(5, 3);  // Expected: 8
let result2 = addNumbers(4.5, 2.5);  // Expected: 7
let result3 = addNumbers('hello', 3);  // Expected: 'Both inputs should be numbers.'

console.log(The sum of 5 and 3 is: ${result1});
console.log(The sum of 4.5 and 2.5 is: ${result2});
console.log(result3);

Output:

The sum of 5 and 3 is: 8
The sum of 4.5 and 2.5 is: 7
Both inputs should be numbers.

4. Step By Step Explanation

1. Function Definition: We define a function addNumbers that accepts two parameters.

2. Input Validation: Before performing the addition, we check if both inputs are numbers using the typeof operator. If one or both of the inputs are not numbers, the function returns a warning message.

3. Addition and Return: If both inputs are numbers, the function adds them together and returns the result.

4. Tests: Three tests are provided. The first two tests validate number inputs, and the third test showcases the input validation.

This simple function showcases the fundamentals of function definition, input validation, and basic arithmetic in JavaScript.

Comments