Remembering that elements gain or lose electrons, when forming compounds,so that they achieve a full outer shell - let's now look at the reaction between sodium and chlorine.
Example 1: Reaction between sodium and chlorine
A sodium atom loses one electron to achieve a full outer shell and chlorine gains one electron to complete a full outer shell. So when a sodium atom reacts with a chlorine atom, the sodium atom loses its one electron to chlorine. The two ions formed are a sodium ion, Na+ and a chlorine ion Cl-.
The two ions have opposite charges, they attract one another.
The force of attraction between them is an electrostatic one. This type of attraction is strong. It is called an ionic or electrovalent bond.
Example 2: Reaction between magnesium and oxygen
Other metals and non-metals react together to form ionic compounds This is because metals tend to lose electrons, whereas non-metals tend to gain electrons.
A magnesium atom has two electrons in its outer shell, whereas oxygen has six electrons. This means that magnesium wants to lose two (to oxygen) and oxygen wants to gain two (from magnesium) so that they can have full outer shells.
The ions attract each other due to their opposite charges. Magnesium ions and oxide ions are formed. The product is magnesium oxide, MgO.
Example 3: Reaction between magnesium and chlorine
To obtain full outer shells magnesium must lose two electrons and chlorine must gain one electron. So when we react magnesium in chlorine, one magnesium atom reacts with two chlorine atoms to form magnesium chloride, MgCl2.