Pigmentation or hyperpigmentation appears because of a protein called melanin produced by cells called melanocytes. The production of melanin is one of the most fascinating defense mechanisms of the skin. When the skin is damaged through a wound, or when there is exposure to harmful UVA/UVB radiation through the sun. The skin gets protective of itself, and melanocytes start over producing melanin. The deposit of melanin in the outer layer of the skin ensures the restriction of external irritants or potentially harmful elements (like UVA UVB rays) from entering the body and causes DNA alterations.
Therefore, when skin cells are damaged or are unhealthy, they can produce excessive melanin causing melanin to clump and the appearance of dark patches on the skin, tanning or brown/black spots.