A full and stable outer shell of an electron consists of eight electrons. In chemistry, this is called the "octet rule". An atom will look to chemically combine with another atom to form a compound or a molecule if it has less than eight electrons. This can be done via either covalent or ionic bonding.
Nonmetals have 4 or more valence (outer shell) electrons while metals tend to have 4 or less.
Two nonmental tend to form covalent bonds by sharing electrons. An electron that is shared goes towards both of the atoms' octets.
When a metal and a nonmetal combine, an ionic bond is created. It is easier for the metals, which have 4 or less electrons, to lose electrons. Metals lose all the valence electrons of their current outer shell. In this way, the shell directly beneath the previous shell becomes its full outer shell. Likewise, the nonmetals gain enough electrons from the metals to complete their octet.