The ancient law was that if a man died, his brother was supposed to have a child by his widow so the line wouldn't become extinct. Therefore, whenEr died, it was up to his brother Onan to perform the duty with Er's widow, Tamar. Because Onan knew that the child to be born wouldn't really be his, he refused and "spilled his semen on the ground" instead (Genesis 38:9). As a result, God killed him.
This story is dismal enough in itself, but later generations have made it more so. Onanism has become a euphemism for masturbation, and the punishment Onan received has been interpreted as meaning that God is, to say the least, against it. Actually what God was against was that Onan had disobeyed the law of levirate marriage and had done so on the unedifying grounds that he didn't want any children of his running around with another man's name. Presumably the punishment would have been just as severe if, instead of doing what he did, he'd simply caught the next bus out of town.
According to Dr. Kinsey, some 92 percent of all males have masturbated, as have some 62 percent of all women. The only damage to come of it seems to be the crippling sense of guilt and terror inculcated by well-meaning, pious folk who, forgetting their own sexual past, say that it makes you go crazy or blind or have your hair fall out.
There seem to be no scriptural grounds for condemning masturbation in itself. Like sex in general, if it is practiced to the exclusion of a loving relationship with other human beings, it is an infraction of the law of love and is its own punishment. On the other hand, if it's practiced as a temporary expedient until the right person comes along, it is harmless. It was not for his sexuality that Onan was punished, but for his stinginess and selfishness and general cussedness.
~originally published in Peculiar Treasures and later in Beyond Words