A simple calculator coded in JavaScript

Took 19 minutes and 28 seconds to code a simple calculator in JavaScript. Here is the code snippet.


Code (Run Code):

function calculator() {
var operand1 = Number(document.getElementById('operand1').value);
var operator = document.getElementById('operator').value;
var operand2 = Number(document.getElementById('operand2').value);
switch(operator) {
case '+':
text = operand1 + ' + ' + operand2 + ' = ' + (operand1 + operand2);
break;
case '-':
text = operand1 + ' - ' + operand2 + ' = ' + (operand1 - operand2);
break;
case 'x':
case '*':
text = operand1 + ' x ' + operand2 + ' = ' + (operand1 * operand2);
break;
case '/':
text = operand1 + ' / ' + operand2 + ' = ' + (operand1 / operand2);
break;
case '**':
text = operand1 + ' ** ' + operand2 + ' = ' + (operand1 ** operand2);
break;
case '%':
text = operand1 + ' % ' + operand2 + ' = ' + (operand1 % operand2);
break;
default:
text = 'Sorry we could not calculate your equation';
}

if (isNaN(operand1) || isNaN(operand2)) {
text = 'Sorry we could not calculate your equation';
}

document.getElementById('result').innerHTML = text;
}

No comments:

Post a Comment

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...