Addition program in javascript

JavaScript Program to Add Two Numbers

In this article, you will learn and get code for the addition of two numbers in JavaScript. The program is created in the following ways:

  • Simple JavaScript Code to Add Two Numbers
  • Add two numbers using a form and a text box.
  • Receive input from the user one by one.

Add two numbers in JavaScript

Here is the simplest JavaScript code to add two numbers.

var numOne = 10; var numTwo = 20; var sum = numOne+numTwo;

As you can see from the above three lines of JavaScript code, the value 10 gets initialized to numOne. So numOne=10. And the value 20 gets initialized to numTwo. So numTwo=20. Now the statement numOne+numTwo, 10+20, or 30 gets initialized to sum. So sum=30, which is the addition of two numbers stored in numOne and numTwo.

On the same concept as mentioned above, I’m going to create another JavaScript code that also adds two numbers and displays the result as an HTML output.

JavaScript: Add Two Numbers in HTML

Here is the JavaScript program that adds two numbers and displays the addition result on a webpage using HTML:

doctype html> html> head> title>Add Two Numberstitle> script> var numOne = 10; var numTwo = 20; var sum = numOne+numTwo; document.write("Sum red">script> head> body> body> html>

Save this code in a file with .html extension. Open the file in a web browser. Here is the output you will see:

Читайте также:  This is my page

javascript add two numbers

Note: The document.write() method writes the value passed in its braces () into an HTML output.

JavaScript: Add Two Numbers Using a Form and TextBox

This is the actual program to add two numbers in JavaScript using forms and text boxes. As this program allows the user to input the data. On the basis of user input, JavaScript code output the addition result.

doctype html> html> head> script> function add() < var numOne, numTwo, sum; numOne = parseInt(document.getElementById("first").value); numTwo = parseInt(document.getElementById("second").value); sum = numOne + numTwo; document.getElementById("answer").value = sum; > script> head> body> p>Enter the First Number: input id="first">p> p>Enter the Second Number: input id="second">p> button onclick="add()">Addbutton> p>Sum = input id="answer">p> body> html>

Here is its sample run with user input: 40 as the first number and 50 as the second number:

add two numbers in javascript

When the user clicks on the button Add, then a function named add() gets called. And all the statements of this function get executed. The following statement:

numOne = parseInt(document.getElementById("first").value);

states that an int (integer) value of an HTML element whose id is first gets initialized to numOne. And the statement:

document.getElementById("answer").value = sum;

states that the value of sum gets printed to an HTML element with the id answer.

Live Output of the Previous Program

Following is the live output of the above JavaScript code on the addition of two numbers:

Get user input one by one

Let’s create one more interesting JavaScript program that does the same job as the previous program, that is, receives two numbers from the user and outputs its addition result.

This program receives input from the user in such a way that the user is allowed to input one at a time.

doctype html> html> head> script> var numOne, numTwo, sum; function getFirNum() < numOne = parseInt(document.getElementById("first").value); if(numOne) < temp = document.getElementById("paraOne"); temp.style.display = "none"; temp = document.getElementById("paraTwo"); temp.style.display = "block"; > > function getSecNum() < numTwo = parseInt(document.getElementById("second").value); if(numOne && numTwo) < temp = document.getElementById("paraOne"); temp.style.display = "none"; temp = document.getElementById("paraTwo"); temp.style.display = "none"; sum = numOne + numTwo; temp = document.getElementById("paraThree"); temp.style.display = "block"; document.getElementById("res").innerHTML = sum; > > script> head> body> p id="paraOne">Enter First Number: input id="first"> button onclick="getFirNum()">Enterbutton>p> p id="paraTwo" style="display:none;">Enter Second Number: input id="second"> button onclick="getSecNum()">Addbutton>p> p id="paraThree" style="display:none;">Sum = span id="res">span>p> body> html>

Here is the snapshot that shows the initial output produced by the above JavaScript program on the addition of two numbers entered by the user:

add two numbers using form javascript

Now enter the first number, say 50, and click on the «Enter» button. Here is the output after performing this:

add two numbers using textbox javascript

Now enter the second number, say 40, and click on the «Add» button. Here is the output that shows the addition result of the two numbers entered:

javascript add two numbers with user input

is a CSS code that hides an HTML element where it is included. Because it is included in a p (paragraph) tag whose id is paraTwo, this paragraph gets hidden initially. The following JavaScript code:

states that, an HTML element whose id is stored in temp variable, gets visible after executing this statement. And the following statement:

works same as previous. The only difference is, this statement hides an HTML element. And the JavaScript code:

document.getElementById("res").innerHTML = sum;

states that the content of an HTML element with id res gets replaced with the value of sum.

Live Output of the Previous Program

This is another live output produced by the previous JavaScript program:

Liked this article? Share it!

Источник

Performing Addition in JavaScript — A Guide

In order to incorporate decimal numbers, the regular expression can be improved to cover them. After that, we need to iterate through the array that is returned, check if the current element is an operator, and perform the necessary calculations. However, including decimal numbers would be problematic since the dot would not be identified as a number, resulting in the separation of a decimal number into two parts.

Performing arithmetic operations on two inputs in JavaScript

The updated version of your code is available at http://jsfiddle.net/v56fkaww/6/ after I made some changes.

The mistake made was not enclosing the function call within an anonymous function.

//Event Listeners firstNum.addEventListener("input",function()); secondNum.addEventListener("input",function()); 

All appears to be in order, save for a minor issue.

firstNum.addEventListener("input", mainFunction()); 
firstNum.addEventListener("input", mainFunction); 

As the function is already defined, it only requires a reference to be passed since it expects a function.

Code :

I enhanced the code by incorporating features for every operator and reduced its length.

//Variables let firstNum = document.getElementById("num1"), secondNum = document.getElementById("num2"), result = document.getElementById("result");//Event Listeners firstNum.addEventListener("input", mainFunction); secondNum.addEventListener("input", mainFunction); result.addEventListener("input", mainFunction);//Main JavaScript function mainFunction() < var one = +firstNum.value||0; // convert to number var two = +secondNum.value||0; // convert to number var opt = document.getElementById("options"); // this is the shorter than what you are using result.innerHTML = opt.options[0] ? one + two : opt.options[1] ? one - two : opt.options[2] ? one * two : one / two; >

An alternative method to evaluate an operator is possible without having to execute switch or if . This approach involves utilizing a Function constructor and performing an immediate execution, as shown in result.innerHTML = (new Function(«return «+one+operator+two))(); .

//Variables let firstNum = document.getElementById("num1"); let secondNum = document.getElementById("num2"); let result = document.getElementById("result"); let operator = document.getElementById("options").value; //Event Listeners //You should asign the function itself not the result like mainFunction() firstNum.addEventListener("input", mainFunction); secondNum.addEventListener("input", mainFunction); result.addEventListener("input", mainFunction); //All of this is like something.addEventListener("input", function()); function mainFunction() < var one = parseFloat(firstNum.value) || 0; var two = parseFloat(secondNum.value) || 0; //evaluate the operator as a javascipt operator not just as string result.innerHTML = (new Function("return "+one+operator+two))(); >

JavaScript Program to Add Two Numbers, The above program asks the user to enter two numbers. Here, prompt () is used to take inputs from the user. parseInt () is used to convert the user input string to number. const num1 = parseInt(prompt (‘Enter the first number ‘)); const num2 = parseInt(prompt (‘Enter the second number ‘)); Then, the sum of the numbers is computed.

How to perform addition operation using string template in Javascript

Perhaps this is the solution you seek.

let arr = [1,3]; console.log(`Adittion is $ + $`);// or console.log(`Addition is $<(arr[0]? arr[0]: 0) + (arr[1] ? arr[1] : 0)>`);// If the socond one is the one you wanted, you can do it using reduce instead summing all positionsconsole.log(`Addition is $a+b)>`);

This is the second example provided. In contrast to the first one, this one employs an array of objects instead of numbers and the approach taken is dissimilar.

When the situation changes from your previous inquiry, it may be beneficial to pose a fresh question.

//In Your second sample you are using an array of objects, not an array of numbers so the implementation is differentlet arr = [,];arr.map(a=>`)>)//If you only want the total it would beconsole.log(`No. of payments $a.card + a.cash).reduce((a,b)=>a+b)>`)

In order for it to function, it is necessary to enclose both operands within a single set of brackets.

I utilized the || (operand selector operator or logical or) to obtain the desired outcome, which I find to be more comprehensible.

Here are some methods to accomplish this:

let arr = [1,3];// Method 1 console.log('Addition is ', (arr[0] ? arr[0]: 0) + (arr[1] ? arr[1] : 0));// Method 2 console.log(`Addition is $<(arr[0]? arr[0]: 0) + (arr[1] ? arr[1] : 0)>`);// Method 3 var sum = [1,3].reduce((a, b) => a + b, 0); console.log('Addition is ', sum);// Method 4 function addition(. elements) < let total = 0; for (const elem of elements) < total += elem; >return total; >console.log('Addition is ', addition(. arr));

Performing arithmetic operations on two inputs in, Performing arithmetic operations on two inputs in JavaScript. I am trying to add two numbers that a user enters, and returning the sum, difference, product or the quotient of two values the user enters. For that, I made two inputs with a drop-down list between that. The drop down list has options to add, …

Chaining multiple operations in a JavaScript Calculator

The calculation result for the string «1+2*3» is incorrect.

var str = "124-2+3*10"; var calculation = str.match(/\d+|[^0-9]/g); var result; for (var a = 0; a < calculation.length; a++) < if (a == 0) < result = parseInt(calculation[a]); >else < if (!isNaN(calculation[a])) < switch (calculation[a - 1]) < case "-": result -= parseInt(calculation[a]); break; case "+": result += parseInt(calculation[a]); break; case "*": result *= parseInt(calculation[a]); break; case "/": result /= parseInt(calculation[a]); break; >> > > console.log(result);

Assume we input a computation such as «1+2+2» in the calculator and press the equal button. When the equal button’s click event handler is triggered, it converts the given string into an array of individual characters.

The input consists of the numbers 1, 2, and 2 combined with addition symbols.

let calculation = display.innerHTML.split(''); 

While this method works well for calculating single-digit numbers, it is not effective for larger numbers.

For instance, if we take the expression «12+2+2», we can represent it as an array of strings where each number and arithmetic operator is separated as an element in the array. This would result in the array [«1», «2», «+», «2», «+», «2»].

A regular expression can be used to separate the operators from the numbers in a more sophisticated manner.

Now, let’s consider another instance where we will utilize the subsequent computation.

Input this string into the given regex pattern.

var calculation = str.match(/\d+|[^0-9]/g); 

The resulting array will appear somewhat similar to this.

The array contains the following values: 124, hyphen, 2, plus, 3, asterisk, and 10.

The operator \ \ \ \ \ \d\+\ \ \ \ matches all numerical values, whereas [^0-9] matches anything that does not qualify as a number.

In case decimal numbers are to be included, the aforementioned method would not work as the dot would not be considered a number. Consequently, it would result in the splitting of a decimal number into two parts.

To address this issue, we can improve the regular expression to encompass decimal numbers, such as:

var calculation = str.match(/\d+\.\d+|\d+|[^0-9]/g); 

At present, the task is to iterate through the array that was returned, identify whether the current element is an operator, and perform the mathematical calculation accordingly.

The isNan(input) function serves the purpose of determining whether the input is a number or an operator. Initially, it attempts to convert the input to a number. However, if this conversion fails, the function returns false.

var str = "124-2+3*10"; var calculation = str.match(/\d+|[^0-9]/g); var result; for (var a = 0; a < calculation.length; a++) < if (a == 0) < result = parseInt(calculation[a]); >else < if (!isNaN(calculation[a])) < switch (calculation[a - 1]) < case "-": result -= parseInt(calculation[a]); break; case "+": result += parseInt(calculation[a]); break; case "*": result *= parseInt(calculation[a]); break; case "/": result /= parseInt(calculation[a]); break; >> > > console.log(result);

Kindly keep in mind that this method of calculation is not the usual way of doing it. Moreover, negative numbers are not considered in this solution. This approach is only intended to serve as a starting point.

How to perform addition operation using string template, Browse other questions tagged javascript arrays ecmascript-6 or ask your own question. The Overflow Blog Great engineering cultures are built on social learning communities

Источник

Оцените статью