Energy from the flame disturbs electrons in sodium atoms. The electrons move into higher-energy states, but they do not remain there. When they fall back, the atoms release packets of light.
The allowed energy levels are not a smooth ramp. They are more like specific steps. Because only certain energy changes are allowed, only certain photon energies—and therefore colors—appear. Through a spectroscope, one bright color becomes a pattern of sharp lines.
Every element carries its own line pattern. Scientists can identify gases in a classroom tube, elements in a distant star, and chemical traces in an unknown sample without touching the source.