Here's a breakdown:
* Magnesium (Mg) is in group 2 of the periodic table, meaning it has 2 valence electrons (electrons in its outermost shell). It readily loses these two electrons to achieve a stable, full outer shell, becoming a magnesium ion (Mg²⁺) with a +2 charge.
* Chlorine (Cl) is in group 17 of the periodic table, meaning it has 7 valence electrons. It needs one more electron to achieve a stable, full outer shell. It gains an electron to become a chloride ion (Cl⁻) with a -1 charge.
To achieve electrical neutrality (where the positive and negative charges balance), two chloride ions (2 x -1 = -2) are required to balance the +2 charge of the magnesium ion.
This forms the ionic compound MgCl₂, where the strong electrostatic attraction between the oppositely charged ions holds the compound together.