Ions form when atoms gain or lose electrons to achieve stable electron configurations, typically following the octet rule. The number of electrons lost or gained determines the charge of the resulting ion.
From electron configuration, you know that atoms arrange their electrons in shells and subshells, and that noble gases have completely filled outer shells. Ion formation is driven by the energetic advantage of achieving or approaching these stable configurations. Atoms do not gain or lose electrons randomly — the number they transfer is determined by how close they already are to a full outer shell.
Cations (positive ions) form when atoms lose electrons. Metals on the left side of the periodic table have just one, two, or three valence electrons. Removing those electrons is energetically favorable because the atom reaches the stable configuration of the preceding noble gas. Sodium (Na), with the configuration 1s²2s²2p⁶3s¹, loses its single 3s electron to become Na⁺, which has the same electron configuration as neon. The energy required to remove this electron (ionization energy) is modest because the atom gains so much stability in return. Magnesium loses two electrons to form Mg²⁺, and aluminum loses three to form Al³⁺ — each reaching the neon configuration.
Anions (negative ions) form when atoms gain electrons. Nonmetals on the right side of the periodic table are just one, two, or three electrons short of a full outer shell. Chlorine (Cl), with configuration [Ne]3s²3p⁵, needs only one electron to complete its 3p subshell and reach the argon configuration, so it forms Cl⁻. Oxygen gains two electrons to form O²⁻, and nitrogen gains three to form N³⁻. The energy released when an atom gains an electron (electron affinity) reflects how strongly the atom pulls that electron into its nearly complete shell.
The pattern connects directly to periodic table position. Group 1 metals form 1+ ions, Group 2 form 2+ ions, Group 16 nonmetals form 2− ions, and Group 17 form 1− ions. Transition metals are more complex — they can form multiple oxidation states because their d electrons are close in energy to their outermost s electrons. The key principle is always the same: electron transfer occurs because the resulting ion has a more stable electron configuration than the neutral atom, and the charge of the ion tells you exactly how many electrons were transferred.