The thought is father to the deed Any form of sexual activity whether between two unmarried people orone alone, is a sin because ti betrays immoral thoughts.
The point being that without the immoral thoughts that accompany it, and in fact are necessary to make it possible, there is no masturbation therefore masturbation is a sin and the evidence of a sin.
It has nothing to do, however, with the famous story of Onan spilling his seed on the ground. That was a whole other sin, and one directly against God rather than just against oneself, as masturbation is. By doing what he did Onan was refusing his responsibility of Brother-in Law marriage under the mosaic Law, a law designed to protect and care for widows.