So, 2 important factors influencing whether a compound is formed through ionic or covalent bonding are:
1) Number of valence shell electrons. The transfer (ionic bonding) or the sharing (covalent bonding) of electrons that leads to chemical formation depends on how close to a full valence shell each element is. If one element's valence shell is almost full, it'll be more likely to overpower an electron that is all by itself in another element's valence shell. So it happens in Na, where there's only one valence electron, whereas in Cl, there are 7, one away from a full shell. But if both elements have similar numbers of valence electrons as in oxygen, neither has a distinct advantage in being able to snatch the electrons needed to get to 8. But, both may achieve the complete 8 if they share.
2) Total number of protons for each element. There are two factors to re-visit: the distance the electrons are from the protons, and the number of protons. Collectively, the more protons there are, the more attractive force they will exert on the nearest electrons. So in elements with a lot of protons, those nearest are really hard to rip away, as occurs in NaCl where Cl has significantly more protons than Na. Both use the 3rd shell for their valence shell, so each set of valence electrons are about the "same" distance away from their respective protons' force. Yet with Na, there are fewer protons, and thus less attractive force imposed upon that valence electron, whereas in Cl, there are more protons and thus more attractive force on its valence electrons. So Na's valence electron becomes somewhat easy to steal. If both elements have similar attractive force power, the elements share rather than steal, as in our example of oxygen.
This snatching and sharing is all to get to 8 valence electron, or complete shell status. But why 8? Didn't we learn that the 3rd orbital holds a maximum of 18 electrons? Think Noble gas. We'll get back to this point.