I am new to modular JavaScript code, and after reading an article on the Internet, I wrote a very basic calculator. This works fine, but due to some unknown reason, I feel that this code is not well written. I will appreciate it if someone could improve my code below so that it will be helpful with learning modular JavaScript.
$(function () {
$('.button').on('click', function() {
var operator = $(this).attr('name'),
calc = new Calculator('output', 'valOne', 'valTwo', operator);
calc.init();
});
});
calculator.js
var Calculator = function(eq, valone, valtwo, operator) {
var eqCtl = document.getElementById(eq),
valone = document.getElementById(valone),
valtwo = document.getElementById(valtwo),
op = operator,
init = function() {
op = operator;
val1 = parseInt($(valone).val());
val2 = parseInt($(valtwo).val());
calculation();
},
setVal = function(val) {
eqCtl.innerHTML = val;
},
calculation = function() {
if(op == 'add') {
addition(val1, val2);
}
else if(op == 'sub') {
subtract(val1, val2);
}
else if(op == 'mult') {
multiply(val1, val2);
}
else {
division(val1, val2);
}
},
addition = function(x,y) {
return setVal(x + y);
},
subtract = function(x,y) {
return setVal(x - y);
},
multiply = function(x,y) {
return setVal(x * y);
},
division = function(x,y) {
if( y == 0 ) {
return setVal('cannot divide by 0');
} else {
return setVal(x / y);
}
};
return {
init: init
};
};
y == 0
indivision
? Javascript's Numbers can have a value ofInfinity
(or-Infinity
), which is returned when you divide by 0 and works as you'd expect it to work. It doesn't throw an error. \$\endgroup\$