Male masturbation appears, from a biological point of view, to be a rather bad idea: you're simply wasting sperm that you could use to fertilise mates. For that matter, you're losing some nutrients and water, as well. But, when we look at the admittedly small number of studies into this kind of thing among mammals, we find that it's not just humans who do it, or even just primates. So, why is that?
The obvious answer, from a human perspective, is that they enjoy it. Or, to put it more biological terms, that the animals have a sex drive that compels them to mate with females, and, in the absence of females, they'll take the next best option. It's worth noting that humans are unusual among mammals (although not unique) in that they don't come into heat, and are willing to have sex at pretty much any time. This means that, when it comes to non-human mammals, we would expect them to masturbate more frequently at times when the female is in heat, since that's the sort of thing they find sexually exciting. Secondly, they will do it more often when they can't get at any females, perhaps because bigger males are getting there first.
But is this what really happens? A recent study looked at this, and a number of other possible explanations, to find out just why squirrels masturbate.