Electrons inside an atom occupy only certain allowed orbitals with a specific energy. In other words, the energy of an electron in an atom is not continuous, but 'quantized.' The energies corresponding to each of the allowed orbitals are called energy levels. An electron shell, or a principal energy level, may be thought of as an orbit followed by electrons round an atoms nucleus.The closest shell to the nucleus is called the "1 shell" (also called "K shell"), followed by the "2 shell" (or "L shell"), then the "3 shell" (or "M shell"), and so on farther and farther from the nucleus. The shells correspond with the principal quantum numbers (n = 1, 2, 3, 4 ...)
Each shell can contain only a fixed number of electrons. The first shell can hold up to two electrons, the second shell can hold up to eight electrons, the third shell can hold up to 18 and so on. The general formula is that the nth shell can in principle hold up to 2(n2) electrons Electrons in outer shells have higher average energy and travel farther from the nucleus than those in inner shells..
Magnesium has an atomic number of 12 .The electron configuration for Mg is 1s²2s²2p⁶3s².
The highest principal quantum number in magnesium's electron configuration is n = 3, so all electrons with n = 3 are valence electrons. Magnesium has 2 valence electrons in its highest energy level.