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

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...