optimised javascript function