In this example, you will learn how to add, subtract, multiply and divide two numbers entered by the user in JavaScript.
To take the user input we will use the prompt()
function of JavaScript.
Example:
// Ask for the user input let num1 = Number(prompt('Enter first number: ')); let num2 = Number(prompt('Enter second number: ')); // Add two numbers(+) let sum = num1 + num2; console.log(`The sum of ${num1} and ${num2} is ${sum}`); // Subtract two numbers(-) let difference = num1 - num2; console.log(`The difference of ${num1} and ${num2} is ${difference}`); // Multiply two numbers(*) let multiplication = num1 * num2; console.log(`The multiplication of ${num1} and ${num2} is ${multiplication}`); // Divide two numbers(/) let divison = num1 / num2; console.log(`The divison of ${num1} and ${num2} is ${divison}`);
Output:
Enter first number: 20 Enter second number: 10 The sum of 20 and 10 is 30 The difference of 20 and 10 is 10 The multiplication of 20 and 10 is 200 The divison of 20 and 10 is 2
The above program first asks the user to enter two numbers. To take input from the user we have used the prompt()
function.
But, the prompt()
function returns the value entered by the user as a string, therefore, we converted it to a number using the Number()
function.
let num1 = Number(prompt('Enter first number: ')); let num2 = Number(prompt('Enter second number: '));
Next, to calculate the sum of the two numbers, we used the addition operator(+) and displayed their sum using the console.log()
function:
let sum = num1 + num2; console.log(`The sum of ${num1} and ${num2} is ${sum}`);
To calculate the difference of both numbers, we use the subtraction operator(-) and then displayed their difference:
let difference = num1 - num2; console.log(`The difference of ${num1} and ${num2} is ${difference}`);
Similarly, to calculate the multiplication of both numbers we used the multiplication operator(*) and displayed the result:
let multiplication = num1 * num2; console.log(`The multiplication of ${num1} and ${num2} is ${multiplication}`);
Finally, to calculate the division of the two numbers, we used the division operator(/) and displayed the result using the console.log()
function:
let divison = num1 / num2; console.log(`The divison of ${num1} and ${num2} is ${divison}`);