refactoring the JS code and adding some comments