To understand this phenomenon, you need to know about phototaxis. Phototaxis is an organism's automatic movement toward or away from light. Cockroaches are an example of a negatively phototactic organism. You've probably noticed how they scurry back into dark corners and crevices when you illuminate their late-night snacking party in your kitchen.
Moths are positively phototactic. They seem charmed by your porch light, your headlights or your campfire (even if it leads to their untimely demise). While there is no definitive explanation for this phenomenon, there are some interesting theories.
Some types of moths are known to migrate, and it's possible that the night sky gives them navigational clues. A moth's up-down orientation might depend in part on the brightness of the sky relative to the ground.
It's also possible that moths have an escape-route mechanism related to light. Imagine disturbing a bush-full of moths at night – they all fly up and out of the bush, toward the sky.
To a moth in danger, flying toward the light (which is usually in the sky, or at least upward) tends to be a more advantageous response than flying towards darkness (which is usually downward).
This is an edited answer from Why are moths fatally attracted to light? which originally appeared on Quora: The best answer to any question. Ask a question, get a great answer. Learn from experts and get insider knowledge. You can follow Quora on Twitter, Facebook, and Google+.