We will discuss the formation NaCl ionic compounds. Ionic compounds are formed between a metal and a nonmetal. Sodium for example is located under Group I. Therefore following octet rule, it will lose one electron to achieve previous noble gas configuration which is equivalent to Neon [2s22p6] and the charge of the sodium ion will be +1.
Similarly, chlorine a nonmetal is located under main group seven. Therefore it has seven valence electrons. Chlorine tens to gain one more valence electronsto achieve next noble gas configuration of Ar [3s23p6]. The charge of the chlorine ion is -1.
When the sodium metal is brought in close contact with chlorine nonmetal, sodium loses electron, chlorine gains electrons and forming ionic bonds due to the electrostatic attraction between the cation and the anion formed Therefore in an ionic compound total charge must be zero.
Following diagram may help to understand the NaCl crystal structure.