Two kinds of road salt sit side by side in a hardware shop: sodium chloride, NaCl, and calcium chloride, CaCl2. Both are a metal ion with chloride ions, yet calcium chloride has two chlorides per metal ion. The reason is charge. Sodium forms Na+ and calcium forms Ca2+, while each chloride is Cl−. A crystal must be neutral overall, so one Na+ pairs with one Cl−, but one Ca2+ needs two: +2+2(−1)=0.
The general move is to find the lowest common multiple of the two charges. Aluminium (+3) and oxide (−2) meet at 6: two aluminiums give +6 and three oxides give −6, so the formula is Al2O3. The crisscross shortcut, swapping the charge numbers into subscripts, gives the same answer here, but it has to be reduced afterwards: Mg2+ and O2− crisscross to Mg2O2, which simplifies to MgO. Polyatomic ions such as nitrate, NO3−, act as single units; when you need more than one, put the whole ion in parentheses: Mg(NO3)2.
Compounds of two nonmetals do not follow the charge rule, because their atoms share electrons instead of forming ions. Carbon and oxygen make both CO and CO2, and nitrogen and oxygen make several compounds, so their formulas come from the prefixes in the name: dinitrogen tetroxide is N2O4. Those subscripts are never reduced, since NO2 is a different gas. If a metal or ammonium is involved, balance charges; if both elements are nonmetals, read the prefixes.
Think of it like this. Writing an ionic formula is like levelling a seesaw with +3 weights on one side and −2 weights on the other: it balances only with two of the first and three of the second, and you always use the fewest weights that work. Compounds of two nonmetals don't use the seesaw; their formulas come from their names.
Core idea. An ionic compound has no overall charge, so its formula uses the smallest whole numbers of cations and anions whose charges cancel, with polyatomic ions kept intact as units in parentheses.