js refactor; thanks to Dave