OneBite.Dev - Coding blog in a bite size

add numbers in javascript

Code snippet for how to how to add numbers in javascript with sample and detail explanation

JavaScript is a powerful, versatile programming language commonly used for making web pages interactive and dynamic. In this article, we’ll walk you through a simple task you can accomplish with JavaScript: adding numbers.

Code snippet for Adding Numbers

Here is a simple JavaScript code snippet that adds two numbers:

let number1 = 10;
let number2 = 20;
let sum = number1 + number2;
console.log(sum);  // Outputs: 30

Code Explanation for Adding Numbers

Let’s break down what this code is doing, line by line.

The first line let number1 = 10; is declaring a variable called number1 and assigning it the numerical value of 10.

The second line let number2 = 20; is doing the same as the first line, but for a variable called number2 with a numerical value of 20.

The third line let sum = number1 + number2; is creating a new variable, sum. We assign to sum the result of adding together number1 and number2 using the plus operator +. In JavaScript, the + operator is used to perform addition when used with numbers.

Finally, the line console.log(sum); is using the console.log function. In JavaScript, console.log is a function that logs output to the console (like the web browser’s JavaScript console, or Node.js’s terminal), which is very useful for debugging and understanding code flow. Here, we are logging the value of sum, which would print the output 30 to the console.

These basic principles for adding numbers in JavaScript can be extended to include more complex calculations and for handling input dynamically from users. Use this as a starting point to explore more of what you can do with math and JavaScript.

javascript