Improved JS function snippet