Metals are elements that tend to lose electrons easily, while nonmetals are elements that tend to gain electrons easily. When a metal and a nonmetal react, the metal atoms lose electrons to the nonmetal atoms, resulting in the formation of positive metal ions and negative nonmetal ions. These ions then combine to form a compound.
For example, when sodium (a metal) reacts with chlorine (a nonmetal), the sodium atoms lose one electron each to the chlorine atoms, resulting in the formation of sodium ions (Na+) and chloride ions (Cl-). These ions then combine to form sodium chloride (NaCl), a compound.