Discussion Locked

JavaScript Calculator Program Error

0 helpful
1 reply
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hello this is Gulshan Negi
Well, I am writing a program for making calculator using JavaScript but it shows some error at the time of its execution.
I am getting error in this phase and here is my source code:

const calculator = {
displayValue: '0',
firstOperand: null,
waitingForSecondOperand: false,
operator: null,
}

function inputDigit(digit) {
const { displayValue, waitingForSecondOperand } = calculator;

if (waitingForSecondOperand === true) {
calculator.displayValue = digit;
calculator.waitingForSecondOperand = false;
} else {
calculator.displayValue = displayValue === '0' ? digit : displayValue + digit;
}
}

function inputDecimal(dot) {
if (calculator.waitingForSecondOperand === true) {
calculator.displayValue = "0."
calculator.waitingForSecondOperand = false;
return
}

I also checked and took a reference from a site but I dont know what thing I am missing.
Can anyone give their suggestions on this ?
Thanks

Note: URL of site referenced removed by moderator.

1 reply

by lokeshjoshi0996

Hi @gulshan212

You can try this code:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Calculator</title>
<script>
function calculate() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
var operator = document.getElementById("operator").value;
var result;

if (operator === "+") {
result = num1 + num2;
} else if (operator === "-") {
result = num1 - num2;
} else if (operator === "*") {
result = num1 * num2;
} else if (operator === "/") {
result = num1 / num2;
}

document.getElementById("result").value = result;
}
</script>
</head>
<body>
<h1>JavaScript Calculator</h1>
<label for="num1">Number 1:</label>
<input type="text" id="num1"><br><br>
<label for="num2">Number 2:</label>
<input type="text" id="num2"><br><br>
<label for="operator">Operator:</label>
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br><br>
<button onclick="calculate()">Calculate</button><br><br>
<label for="result">Result:</label>
<input type="text" id="result" readonly>
</body>
</html>

You can run this code; I hope this will help you. In the code that you shared, add ":" after } in the 6th row. I also checked the reference that you have mentioned the same thing is missing.

This discussion is closed to new replies.