I was reading on how Diffie-Helman works and the wikipedia article has the following:
$(g^a\;\mathrm{mod}\;p)^b\pmod p \equiv (g^b\;\mathrm{mod}\;p)^a\pmod p$
And that equation is true because of the $(g^a)^b=g^{ab}$ property. However what about the $\mathrm{mod}\; p$ part? Is it affected by exponentiation? If not what guarantees that at the end of the calculation both sides of the equation will be equal?
Speaken mathematically, $\mathrm{mod}\; p$ is a ring homomorphism from $\Bbb Z \to \Bbb Z/p\Bbb Z$, i.e. it preserves addition and multiplication. In less math slang, this means
$$ \def\cmod{\;\mathrm{mod}\;} \def\lmod{\mathrm{mod}\;} (a+b) \cmod p = (a\cmod p)+(b\cmod p)$$ $$(a\cdot b) \cmod p = (a\cmod p)\cdot (b\cmod p)$$
These are not too hard to check. But especially the second one is important for your case. Because this gives
\begin{align*} (g^a \cmod p)^b = \overbrace{(g^a \cmod p) \cdots (g^a \cmod p)}^{b\text{ times}} = \overbrace{(g^a)\cdots(g^a)}^{b\text{ times}} \cmod p = (g^a)^b \cmod p \end{align*}
Having this in place, we have
$$ (g^a \cmod p)^b =(g^a)^b \cmod p = (g^b)^a \cmod p =(g^b \cmod p)^a.$$
The second identitiy holds for the reason I already mentioned in the comments: if some identity holds without $\lmod p$, then also with $\lmod p$. And the same now gives
$$(g^a \cmod p)^b \equiv (g^b \cmod p)^a \pmod p.$$