The molecular formula of a compound tells us the elements present in the compound and also the relative ratios in which the elements are present. For NaCl, we can see that there are two elements, sodium and chlorine, and that they are both present on a 1:1 ratio since the subscripts are both one. But for the compound Mg(OH)2 (magnesium hyroxide), the molar ratios are magnesium:oxygen:hydrogen 1:2:2. In other words, for every one atom of magnesium there are two atoms of both oxygen and hydrogen. For Na2SO4 (sodium sulfate), we can tell by the subscripts that for every 2 atoms of sodium there is 1 atom of sufur and 4 atoms of oxygen. The ratios are Na:S:O, 2:1:4. The numerical subscripts always tell us the ratios of the elements to each other in a compound and they do not always form in 1 to 1 ratios with each other.
The ratio between atoms forming a specific compound can be any whole number ratio. For instance, the ratio of hydrogen to oxygen in water is always 2:1, giving us H2O.
The reason atoms combine in whole number ratios is because of the way the atoms join to create a compound. When an atom has an incomplete valence (outer) shell of electrons, it will combine with other atoms in a way that completes that outer shell, usually with 8 electrons. For instance, the element Sodium has just one valence electron, so it will bond with elements like Chlorine, which has 7 valence electrons. Sodium's single electron is transferred to the Chlorine atom, and the Compound NaCl is formed, which always has a 1:1 ratio of Sodium to Chlorine.
However Magnesium has two valence electrons. If Magnesium is to bond with Chlorine, it cannot be in a 1:1 ratio, because a single Chlorine cannot take in both of the Magnesium's valence electrons. So instead a single Magnesium atom will bond with two Chlorines, sharing one of its valence electrons with each, and creating the compound MgCl2, with a 1:2 ratio.