The valence of an atom is determined by the number of electrons in the outermost shell of the atom.
The IUPAC definition limits valence to the maximum number of univalent atoms that may combine with the atom, that is the maximum number of valence bonds that is possible for the given element.
The electron configuration of an atom is most stable when it has one that is similar to the atom of the closest noble gas. To gain a complete octet of electrons atoms can either give their outermost electrons to other atoms or accept electrons and incorporate them into their outermost shell. This is the case with the formation of ionic bonds. Or the electrons may be shared between atoms to form covalent bonds.
Most elements can display different valence when they form bonds and this changes the type and number of bonds formed. The only thing constant is that the electron configuration after the formation of bonds is more stable than what it was before the bonds were formed.