the octet rule
Atoms behave as if they are chasing a particular number of outer electrons: eight. This octet rule says most main-group atoms gain, lose, or share electrons until their outermost shell holds eight, the same full-shell arrangement the noble gases already have and that makes those gases so contentedly unreactive. Eight is the sold-out sign on the outer shell.
Follow the arithmetic for common cases. Sodium has one outer electron; the cheapest way to reach eight is to lose that one, exposing the full shell beneath, becoming Na^+. Chlorine has seven; the cheapest way is to gain one, becoming Cl^-. Together they satisfy each other, sodium's donated electron fills chlorine's shell, and the opposite charges attract into an ionic bond. Carbon has four, too many to easily lose and too many to easily gain, so it shares: four shared pairs give it eight and build covalent networks.
The octet rule is the single most useful beginner's guide to why atoms bond at all, because the whole drive toward bonding is the drive toward a full, stable outer shell. But it is a rule of thumb, not a law. Hydrogen aims for two (a full first shell), not eight; boron is happy with six; and many elements from the third period on can hold more than eight (sulfur in SF6 has twelve). Treat the octet as the default expectation that the exceptions are measured against.
Magnesium (2 outer electrons) loses both to become Mg^2+, while oxygen (6) gains two to become O^2-; each now has a full octet, and the +2 and -2 attract into magnesium oxide, MgO. Two electrons moved, two full shells achieved, the octet rule in action.
Atoms bond to reach a full outer shell; eight is the usual target.
The octet rule works best for the second-period elements (carbon, nitrogen, oxygen, fluorine). Beyond them, expanded octets and electron-deficient molecules are common, so a filled octet is a strong tendency, not an inviolable requirement.