updated js implementation to remove the memory leak