JavaScript(JS) JS make a simple calculator
https://www.theitroad.com
Here's an example of a simple calculator in JavaScript that can perform addition, subtraction, multiplication, and division:
// Function to perform the calculation function calculate(num1, operator, num2) { let result; switch(operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: return "Invalid operator"; } return result; } // Prompt the user for input const num1 = parseFloat(prompt("Enter the first number:")); const operator = prompt("Enter an operator (+, -, *, /):"); const num2 = parseFloat(prompt("Enter the second number:")); // Perform the calculation and display the result const result = calculate(num1, operator, num2); console.log(`The result is: ${result}`);
In this code, we first define a calculate
function that takes in three arguments: num1
, operator
, and num2
. The function uses a switch statement to determine which operation to perform based on the operator
argument, and then returns the result of the calculation.
We then prompt the user to enter the first number, operator, and second number using prompt()
. We parse the input as floats using parseFloat()
to ensure that we can perform mathematical operations on them.
Finally, we call the calculate
function with the user input and store the result in a variable. We then log the result to the console using console.log()
.