commented javascript to make the logic clear