Anodes protect metal components of your boat from dissolving by corroding more readily than they do. That is, anodes sacrifice themselves to preserve the boat. This process occurs via galvanic corrosion - when two metals with different levels of electrical activity, are immersed in the same conductive liquid. A sacrificial anode is a third type of metal (aluminum, magnesium or zinc), which is installed because it is even more electrically active. When electrically connected to them by the liquid, it becomes the material which gives up electrons and dissolves which is why it is know as sacrificing itself, while preserving the original two metals. If you keep replacing the sacrificial anode before it has dissolved, the other less active metal components of your boat remain protected.
Aluminum anodes are rapidly replacing zinc anodes as they're more electrically active and have a longer-term corrosion protection in both brackish and salt water
Magnesium anodes are the most active and the only anodes that work well in the low conductivity of fresh water and is relatively non-toxic to aquatic life