Atoms can complete their outermost energy levels by sharing electrons with other atoms because the shared electrons complete both atoms' octets, resulting in stable electron configurations for both atoms.
In H2O, all three atoms have a complete octet. The bonding looks like this:
where the two lines each represent a pair of electrons and oxygen also has two lone pairs of electrons. Two atoms' shared pairs of bonding electrons count for both atoms' octets. Oxygen has eight electrons - two shared pairs and two bonding pairs. Each hydrogen has two electrons, which are also being shared with oxygen.
There may be some confusion with hydrogen having a complete outer level with only two electrons. Being a small atom with just one proton, it can have 0, 1 or 2 electrons. Two electrons is a full outer level because the first principal energy level only holds two electrons. Hydrogen has the stable electron configuration of the noble gas helium when it has two electrons.
Chemical bonds that result from atoms sharing electrons are called covalent bonds. Most of the time all atoms that are covalently bonded will have 8 outer electrons. There are a few exceptions:
1. Atoms with fewer than six electrons in the neutral atom
2. Atoms with an odd number of electrons
3. A few elements in the third period and lower form compounds in which they have more than 8 outer electrons, involving inner electrons in bonding.