write me a calculator in javascript

We can create a simple calculator in JavaScript by using functions and event listeners. Here is an example code for a basic calculator that can add, subtract, multiply, and divide two numbers:

// Get the input values 
const num1 = document.getElementById("num1").value;
const num2 = document.getElementById("num2").value;
const result = document.getElementById("result");

// Add event listeners to the buttons
document.getElementById("add").addEventListener("click", add);
document.getElementById("subtract").addEventListener("click", subtract);
document.getElementById("multiply").addEventListener("click", multiply);
document.getElementById("divide").addEventListener("click", divide);

// Define the operations
function add() {
  result.value = parseFloat(num1) + parseFloat(num2);
}
function subtract() {
  result.value = parseFloat(num1) - parseFloat(num2);
}
function multiply() {
  result.value = parseFloat(num1) * parseFloat(num2);
}
function divide() {
  result.value = parseFloat(num1) / parseFloat(num2);
}
827 chars
25 lines

In the HTML file, we would need to add the input fields and buttons as well:

<label for="num1">Number 1:</label>
<input type="number" id="num1">
<label for="num2">Number 2:</label>
<input type="number" id="num2">
<button id="add">Add</button>
<button id="subtract">Subtract</button>
<button id="multiply">Multiply</button>
<button id="divide">Divide</button>
<label for="result">Result:</label>
<input type="number" id="result">
352 chars
11 lines

This is a basic example, but you can modify and customize it to add more features and functionalities.

related categories

gistlibby LogSnag