let us consider two elements Na and Cl
In sodium electronic configuration is 2,8,1. If sodium loses one electron ,it will get stable configuration.
By loosing one electron ,Na become `Na^+` ion
In chlorine electronic configuration is 2,8,7 .If chlorine gets one electron ,it will get stable configuration.
By gaining one electron Cl ,changed to `Cl^-` ion.
Thus either by gaining or loosing ,a formation of ions take place.