How do chemists know that the formula of Magnesium Oxide is MgO? That's what this page is all about and to understand it you'll need to know how to determine the charge on an ion, this information can be found here.
Magnesium is in group 2, therefore its ion a charge of 2+. Oxygen is in group 6, therefore its ion has a charge of 2-. Ionic compounds (at GCSE) have an overall charge of zero so the positive and negative charges must be of equal size to cancel each other out. Therefore one magnesium ion (with a charge of 2+) and one oxide ion (with a charge of 2-) are needed to give an overall charge of zero. So the formula is MgO.
Magnesium is in group 2, so its ion has a charge of 2+, chlorine is in group 7 so its ion has a charge of 1-. Therefore you will need two chloride ions (2x1-=2-) for every magnesium ion to give an overall charge of zero, giving a formula of MgCl2
Look at the diagram to the right. Count the number of each ion to get the ratio of ion, in this case it's 8 sodium ions to 8 chloride ions. This is a 1-1 ratio. So the formula of sodium chloride is NaCl.
If the ratio were 2-1 the formula would be Na2Cl, simples!