OneBite.Dev - Coding blog in a bite size

add number in javascript

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

JavaScript, a versatile and popular scripting language, is commonly used in web development for interactive features. In this article, we will explore how to add numbers in JavaScript, a fundamental operation in the programming domain.

Code snippet: Addition in JavaScript

In JavaScript, the addition of numbers is straightforward. Consider the following code:

var num1 = 5;
var num2 = 10;
var sum = num1 + num2;

console.log(sum);

In this snippet, we’re declaring two variables (num1 and num2) and assigning them the values of 5 and 10, respectively. We then declare a third variable sum and assign it the result of adding num1 and num2. Lastly, we log the result to the console.

Code Explanation: Addition in JavaScript

Let’s break down the code to better understand how it functions step-by-step:

  1. var num1 = 5; and var num2 = 10;: Here we declare two variables, num1 and num2, and assign them the values 5 and 10, respectively. These will serve as the two numbers we wish to add.

  2. var sum = num1 + num2;: This line is where the addition happens. JavaScript uses the + operator for addition. We declare a new variable sum and assign it the result of the addition of num1 and num2.

  3. console.log(sum);: Lastly, we use the console.log() function to display the result of the addition on the console. If the code is running correctly, this should display 15—the result of adding 5 and 10.

In conclusion, adding numbers in JavaScript is as simple as using the + operator. It’s a fundamental skill in programming, especially in web development where JavaScript is extensively used.

javascript