Magnesium loses two electrons which are transferred to the oxygen atom (so oxygen gains two electrons). In this way, both magnesium and oxygen will acheive a stable full outer shell of electrons. The electrostatic force of attraction between the positive magnesium ion and negative oxygen ion causes them to be held together in an ionic bond, forming MgO.