write a script for a calculator in javascript

Here's an example script for a calculator in JavaScript:

index.tsx
// Function to perform the calculation
function calculate() {
  // Get the input values
  var num1 = parseFloat(document.getElementById("num1").value);
  var num2 = parseFloat(document.getElementById("num2").value);
  var operator = document.getElementById("operator").value;

  var result;

  // Perform the calculation based on the operator
  switch (operator) {
    case "+":
      result = num1 + num2;
      break;
    case "-":
      result = num1 - num2;
      break;
    case "*":
      result = num1 * num2;
      break;
    case "/":
      result = num1 / num2;
      break;
    default:
      result = "Invalid operator";
  }

  // Display the result
  document.getElementById("result").innerHTML = "Result: " + result;
}
733 chars
31 lines

You can create an HTML page with inputs for two numbers, a select dropdown for the operator (+, -, *, /), a button to trigger the calculation, and a div to display the result. Then, you can add an event listener to the button that calls the calculate function.

<!DOCTYPE html>
<html>
  <body>
    <input type="number" id="num1">
    <select id="operator">
      <option value="+">+</option>
      <option value="-">-</option>
      <option value="*">*</option>
      <option value="/">/</option>
    </select>
    <input type="number" id="num2">
    <button onclick="calculate()">Calculate</button>
    <div id="result"></div>

    <script src="script.js"></script>
  </body>
</html>
423 chars
18 lines

Note that this is a basic example and doesn't include error handling or more complex operations. You can extend it based on your requirements.

related categories

gistlibby LogSnag