When atoms share electrons, they form covalent bonds. In a covalent bond, two atoms share one or more pairs of electrons. This sharing of electrons allows both atoms to achieve a stable electron configuration. For example, when two hydrogen atoms bond to form a hydrogen molecule, each hydrogen atom shares one electron with the other hydrogen atom. This results in both hydrogen atoms having a full outer electron shell, which makes the hydrogen molecule stable.
When atoms gain or lose electrons, they form ionic bonds. In an ionic bond, one atom transfers one or more electrons to another atom. This results in one atom having a positive charge (a cation) and the other atom having a negative charge (an anion). The electrostatic attraction between the positive and negative charges holds the ions together. For example, when sodium and chlorine atoms bond to form sodium chloride, the sodium atom loses one electron to the chlorine atom. This results in the sodium atom having a positive charge and the chlorine atom having a negative charge. The electrostatic attraction between the sodium and chlorine ions holds the sodium chloride crystal together.
In general, atoms will share, gain, or lose electrons in order to achieve a stable electron configuration. This is because a stable electron configuration makes an atom more chemically inert and less likely to react with other atoms.