updated js code to make better use of functionals and closures