In an ionic compound, atoms combine to attain inert gas configuration by losing or gaining electrons.
For example, in an ionic compound, NaCl, sodium (Na) loses one electron to chlorine (Cl) because sodium has one electron more than the nearest inert gas, Neon (Ne) and Chlorine has one electron less than the nearest inert gas configuration, Argon (Ar).
But, in a covalent compound like H2, both the hydrogen atoms require electrons one electron. So, no one atom is ready to lose electrons and hence electron sharing takes place between such atoms resulting in a covalent compound.