While scientists debate the evolutionary reason for masturbation, there's no doubt that humans are not alone in their self-pleasure from time to time.
Many animals that masturbate don't continue the deed until orgasm (humans seem to be rather goal-oriented on this point). That means that some of the best theories for why masturbation evolved in humans are off the table for other animals. For example, studies have found that masturbation can increase a man's sperm count by getting rid of old semen that's lost its vitality, and therefore boosting the chances that young, lively sperm will be ejaculated during intercourse. But since this discharge doesn't seem to occur as often in animals, then there must be some other benefits to the practice.
Dogs like to thrust and rub against objects and enjoy licking themselves. Male horses like to slide their penises against their underbellies. Moose can bring themselves to orgasm simply by rubbing their antlers on nearby trees. Male walruses can use their flippers for masturbation and their mouths for self-fellation. Male turtles will emit squeaks of pleasure while masturbating. Male squirrels masturbate to ejaculation and consume the ejaculate. Masturbation could function as a form of genital grooming, because saliva has anti-bacterial properties, and the act may also reduce risk of catching a sexually transmitted disease. Consuming the ejaculate may prevent moisture loss.
Moskowitz, C. (2011, 23. February). Why So Many Animals Evolved to Masturbate. Live Science.