Atoms bond to fill their outer electron shell. Two nonmetals get there by sharing: a covalent bond is a pair of electrons held between two nuclei, and each atom forms as many as it has room for. Hydrogen makes one, oxygen two, nitrogen three, carbon four. That valence is why water is H2O and methane is CH4, and it is what decides which molecules you can build here.
Shared is rarely equal. Oxygen and nitrogen pull electrons harder than hydrogen or carbon, so their bonds are polar and the molecule can carry partial charges. Whether the whole molecule is polar depends on its shape: water is bent so its charges do not cancel, while carbon dioxide is straight so they do. Shape comes from electron pairs repelling each other, lone pairs included.
A metal and a nonmetal do not share. Sodium gives its one outer electron to chlorine outright, leaving Na+ and Cl-, and the attraction between the two ions is the ionic bond. There is no molecule, only a lattice of ions, which is why salt is a crystal and dissolves into ions in water. Magnesium gives two electrons, so it takes two chlorides.