Are we talking about the clothing that goes on your head, or the drink served after dinner?
A large part of it was just a lack of central heating in a lot of homes prior to the 20th century. Night caps are very effective for keeping warm, but not usually necessary these days.
There's more to it, though. A history teacher of mine once told me they served a secondary purpose. He claimed that oily hair products like pomade were very popular for a time in the 19th century and nightcaps were used to keep bed sheets cleaner. I followed up on it and according to Encyclopedia of Hair: A Cultural History by Victoria Sherrow (p. 323) the explanation is essentially correct.