Refactored Javascript code