A new book, Inside Jokes Using Humor to Reverse-Engineer the Mind, lays out a cognitive and evolutionary perspective on the answer. A reviewer from Science Magazine explains:
The key to the authors' success is that they locate humor within recent cognitive science and evolutionary theory. To aid survival, our brains constantly and covertly use heuristics to generate expectations about what we will experience next, but we would be too inventive for our own good if we did not regularly search for and remove discrepancies between our expectations and our experiences. The immediate incentive to look for such discrepancies and thereby to reduce error comes from the pleasure of discovering a mistake in a currently harmless active belief that was introduced covertly. That pleasure is mirth, and humor is what produces it. Thus, humor is “a cognitive cleanup mechanism” that stains with mistaken belief before washing out the error (as in “I wondered why the Frisbee was getting bigger, and then it hit me.”). Laughter is then a public signal of our ability to clean up our minds. Because such cognitive prowess is useful, it attracts mates—both friends and sexual partners—and spreads throughout the world.
Hurley, Dennett, and Adams apply their theory to well over a hundred examples (including stupid jokes, dark humor, musical jokes, and witty remarks that are not humorous), to many apparent counterexamples (such as surprises, forgetting, riddles, and lies), and to related phenomena (such as magicians and garden-path sentences).