An ionic compound has no overall charge. The total positive charge on its ions must equal the total negative charge, so the compound is neutral. To deduce a formula, write down the charge on each ion and then choose how many of each ion are needed to balance the charges.
Common ions include Na+, K+, Ag+, Mg2+, Ca2+, Al3+, Cl-, Br-, O2-, OH-, NO3-, CO32- and SO42-. Magnesium ions have a charge of 2+ and chloride ions have a charge of 1-, so two chloride ions are needed for each magnesium ion and the formula is MgCl2. Sodium ions are 1+ and carbonate ions are 2-, so two sodium ions are needed for each carbonate ion and the formula is Na2CO3.
Aluminium ions have a charge of 3+ and sulfate ions have a charge of 2-. Two aluminium ions give 6+ and three sulfate ions give 6-, so the formula is Al2(SO4)3. When more than one ion made of several atoms is needed, its formula goes in brackets. Magnesium hydroxide has one magnesium ion and two hydroxide ions, so its formula is Mg(OH)2.