It is so in order to complete their last shell as in the example of sodium there are total 11 electrons and the electric configuration is 2 in K shell , 8 in L shell and 1 in M shell . So in order to complete its last Orbit . It loses 1 electron . Similarly in the case of oxygen the electronic configuration is 2 in K shell and 6 in L shell , show it in order to complete its last Orbit it gains 2 electrons....
May this answer help you