###parsing integers
The function convert()
calls parseInt()
with no second parameter (i.e. radix). The MDN documentation states one should "Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior"1. So that call should have 10
added as the second parameter. And that function doesn't get re-assigned, so const
can be used instead of var
.
const convert = function(a){
return parseInt(a.val(), 10);
}
###Caching DOM references
I agree with kingdao's answer: DOM references should be cached, though they should be cached once per page load instead of each time the function runs. So in the example code, $newAge
and $retireYear
should be declared outside the result
function, and inside the DOM-ready callback (i.e. $(function(){ ...})
).
Also, the names might be a little misleading. For example, the jQuery function (i.e. $(selector)
) returns a jQuery object referencing DOM elements. Thus an appropriate name might be newAgeElements
instead of $newAge
(though you can use the $
if you want). Also, cache the currentYear elements in a constant too.
$(function() { //DOM ready callback
const newAgeElements = $(".newAge");
const retireYearElements = $(".retireYear");
const currentYearElements = $(".currentYear");
//other variables/constants declaration: like currentYear, convert()
const result = (a, b) => {
currentYearElements.text(currentYear)
if (b > a) {
newAgeElements.text(b - a)
retireYearElements.text(currentYear + (b - a))
message1.dialog("open")
} else {
newAgeElements.text(a - b)
retireYearElements.text(currentYear - (a - b))
message2.dialog("open")
}
}
});
For more information about why caching DOM elements is important, read this article. I know it is a few years old and bashes jQuery but it is still relevant and useful.