javascript version finally working correctly