How to Add Two Numbers Using JavaScript

Bahar IsmailBy Bahar Ismail
Featured image for How to Add Two Numbers Using JavaScript

πŸš€ Introduction

Learning to write simple JavaScript functions is one of the best ways to start your programming journey. In this tutorial, you’ll learn how to create a function that adds two numbers together β€” a fundamental building block in any programming language.

πŸ’‘ Why This Matters

Functions are the core building blocks of JavaScript. Understanding how they work helps you:

  • Break your code into reusable pieces
  • Improve readability and debugging
  • Build real-world applications with logic

πŸ‘¨β€πŸ’» Example Code

Here’s a simple JavaScript function that adds two numbers:

function addNumbers (a, b) {

return a + b; }

// Example usage

const sum = addNumbers(5, 7); console.log("The sum is:", sum);

// Output: The sum is: 12

This function accepts two parameters, a and b, and returns their sum. The console.log() statement displays the result in your browser's developer console.

πŸ§ͺ How to Run This Code

To run this snippet:

  1. Open your browser.
  2. Press F12 or right-click and choose Inspect.
  3. Go to the Console tab.
  4. Paste the code and hit Enter.

βœ… What You Learned

  • How to define a JavaScript function
  • How to use parameters and return values
  • How to test the result using console.log()

πŸ” Try It Yourself!

Change the numbers in addNumbers(5, 7) and see how the output changes. Try addNumbers(10, 15) or even pass variables instead of direct numbers.

Reader Comments