They prevent whiplash caused by Newton's First Law.
In a rear-end collision, the car accelerates forward but your head stays in place due to inertia. The headrest pushes your head forward with the car, preventing your neck from snapping backward. It's a life-saving application of the law of inertia.