The prohibition about masturbation derives from a biblical story of Onan. Here is the relevant part of the story:
Genesis 38:1 It happened at that time that Judah went down from his brothers and turned aside to a certain Adullamite, whose name was Hirah.
2 There Judah saw the daughter of a certain Canaanite whose name was Shua. He took her and went in to her,
3 and she conceived and bore a son, and he called his name Er.
4 She conceived again and bore a son, and she called his name Onan.
5 Yet again she bore a son, and she called his name Shelah. Judah was in Chezib when she bore him.
6 And Judah took a wife for Er his firstborn, and her name was Tamar.
7 But Er, Judah's firstborn, was wicked in the sight of the LORD, and the LORD put him to death.
8 Then Judah said to Onan, "Go in to your brother's wife and perform the duty of a brother-in-law to her, and raise up offspring for your brother."
9 But Onan knew that the offspring would not be his. So whenever he went in to his brother's wife he would waste the semen on the ground, so as not to give offspring to his brother.
10 And what he did was wicked in the sight of the LORD, and he put him to death also.
(Gen 38:1-10 ESV)
The 'spilling of seed on the ground' seems to be what the sin was. He did not fulfill his Levirite duty by making sure his deceased brother's wife did not conceive.
Although it can be argued that the context of the story is one of Levirite marriage and not masturbation, it has been seized upon as maintaining that any waste of seed is somehow sinful. I personally find this absurd.
Natural sex drives are normal and expected especially as a young man or woman enters puberty. The sexual impulse is very strong and is nature's way of procreating the spieces which is why we have those impulses when we are young and healthy as opposed to old and sick. Of course, we can't satisfy those needs by having sex with anyone we wish merely to satisfy the procreation impulse. And so to fantasize is our best substitute.
Naturally, if masturbation is excessive and seems to be occupying you mind all the time, there may be other issues that will need to be dealt with. Constantly thinking of sex may indicate the beginnings of an addiction. But masturbation in a normal and healthy person is normal and healthy. It is no sin. The fantasy life is part of who we all and trying to repress that impulse is almost always futile, frustrating and impossible.
Answered by: Rabbi Cy Stanway