refactor js to handle scope correctly