Ionic bonds occur when a more electronegative atom is given an electron from a less electronegative atom. The difference in electronegativity should be more than 2.0. The ionic bond is formed because positive and negative attract, and gaining/losing an electron forms negative/positive ions. (Electronegativity is a measure of the strength of an atom's attraction for valence electrons. Fluorine is the most electronegative element because it has a lot of protons and it does not have a lot of shells of electrons below its valence shell that can shield the valence electrons from the protons' pull). Sodium's electronegativity is 0.93, while chlorine's is 3.16, so the difference is 2.23 and the bond is ionic.
Covalent bonds are formed between atoms with similar electronegativities that share (an) electron(s). One atom is not strong enough to take an electron completely, so the electrons are shared and the shared electrons are counted as belonging to each atom to satisfy the octet rule. The octet rule states that each atom wants eight electrons in its valence shell, although there are some exceptions (Hydrogen follows the duet rule because its valence shell holds only two electrons, boron often has only six electrons, large atoms like xenon can have more than eight electrons, etc).