All animals respire which means that they use oxygen in the process of extracting energy from their foodstuffs, and produce carbon dioxide as a waste product.
Mammals have lungs which provide a huge surface area for air to come into contact with blood so that the oxygen can be bound to haemoglobin and taken around the body. In the same way, fish expose a huge surface area through their gills to the sea, which also contains oxygen dissolved in it.
There is only about 1% oxygen in water compared with around 20% in air, so gills require a huge amount of water to provide the necessary gas exchange.
The gills also pass carbon dioxide into the water in the same way as lungs breathe it out into the air.
As the water passes over the gills, the blood in the fish absorbs oxygen from the water. So as an organ, gills are analogous to lungs in mammals. But why doesn’t the oxygen simply get absorbed from the water through the fish’s body? The problem is the surface area required.
Single-celled animals can absorb oxygen through their surface because their volume is relatively small. But as animals become larger in size, the volume grows faster than the surface area, so it becomes insufficient for absorbing enough oxygen. So as larger animals evolve, they also evolve organs which can expose sufficient surface area to get the necessary oxygen.
In the case of mammals, they brought the air inside the body into lungs which had alveoli, small sacs which exposed a large surface area. Fish, on the other hand need that surface area exposed to water and gills evolved to meet that need.
Having gills exposed on the outside of the fish would be advantageous in that more water would flow past the filaments but that would also expose them to damage. Evolution favoured those fish with the filaments protected in the walls of the larynx, the fish throat, so that water flowed through the mouth and out of the gills, and this enabled currents to swirl the water increasing the exchange of gases.
Lungs evolved as a part of evolutionary adaptation when fish moved onto the land. However, evolution has no purpose because it is based on blind natural selection based on random mutations and in fact, gills have developed from many types of embryonic tissue. In mammals, lungs develop from a fold in the embryonic gastrointestinal tissue.
There are many organisms with different respiratory organs such as some crustaceans that have legs adapted for gas exchange.
It is tempting to think that the gills simply moved inside for mammals but the developmental biology is more complex. Earlier forms of fish had a swim bladder which also formed from the embryonic gastrointestinal tissue and originally had a gas exchange function as well. In modern fish it is simply a swim bladder.
It is a fascinating fact that evolution can produce similar organisms from totally different starting points through the process of natural selection.