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:
- Open your browser.
- Press
F12
or right-click and choose Inspect. - Go to the Console tab.
- 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.