Refactored javscript code