The 4s orbital of an atom usually fills before electrons go into its 3d orbitals because the 4s orbital is slightly lower in energy than the empty 3d orbitals. However, once electrons are in the 3d orbital the 4s is no longer lower in energy so when ionization occurs electrons are lost from the 4s orbital before they're lost from the 3d orbitals.
The 4s and 3d orbitals are very close in distance from the nucleus and therefore in energy. The diagram below shows the energy level overlap between the 4s and 3d orbitals. This occurs between s and d sub levels of other adjacent energy levels as well. Since electrons repel other the energies of orbitals vary depending on how many electrons they contain.
You may have noticed that some transition elements have ground state electron configurations in which the 4s orbital isn't fully occupied but there are electrons in the 3d orbitals. This exception occurs because a full or half-full d sub level gives the atom more stability (lowers the overall energy of its electrons.) It's another example of the switch in positions of s and d orbitals in the energy diagram. Here are some examples:
Chromium: [Ar] 4s1 3d5
Copper: [Ar] 4s1 3d10