refactored javascript code