Variable valency exists due to stability criterions. The actual cause of variable valency has its roots in quantum mechanics, and theories of atomic stability, but we will restrict our discussion to the peripheral ideas.
Atoms lose electrons or gain electrons , and hence change their valency as a step to gain octet or duplet configuration. Consider Cl-, it has 8 electrons in outermost shell, and is hence stable.
But for heavy metals , commonly called transition metals, it is always not easy to attain such perfect stability. This is because, there exists d orbitals and hence they have intermediate conditions called half filled states, which stabilises the atom.
Iron has 2 valence electrons. So its valency should be 2. But it shows 3 also because it has high stability in its half filled electronic configuration, that it attains when it is at 3+ state. Same is true for all other atoms
If you are not comfortable with terms like half filled, dont worry , you will study them in detail. We have s, p, d, f orbitals. S and P orbitals are stable only when they are filled. But d and f are stable when they are half filled too. This is the main reason for the anomalous variable valencies shown.