Flies, moths, beetles and other flying insects that have positive phototaxis are attracted to light. Phototaxis is an organism's automatic response to light. Those with positive phototaxis automatically move toward it. Insects that experience negative phototaxis are repulsed by light. Examples of insects that experience negative phototaxis are earthworms and cockroaches.
Another reason night-flying insects move toward the light is that they are used to navigating by the moon. Artificial lighting attracts and confuses insects. Artificial light bulbs radiate light in many directions, while the moon, stays at a constant angle, which the insects can use for navigation. As a result, artifical light creates confusion, causing the insects to fly in a circle around it.
According to PawNation, it is also believed that some flying insects are attracted to light at night because it confuses them into thinking it is natural daylight.
Another popular theory is that insects fly toward the light at night when they are in danger. The light is usually above them; if they fly up, rather than down into the darkness, their chances at obtaining safety are greater.
Despite these theories, many people wonder why flying insects, such as moths, stay near the light. One reason may be that it takes moths' eyes much longer than human eyes to adapt back to the darkness. It renders them unable to see for much longer than the few seconds humans experience before their eyes adjust.