The content and purpose of dreams are not yet understood, though they have been a topic of speculation and interest throughout recorded history.
Source : Wikipedia
Not only is the function of dreaming unknown (if there is one), but there isn't as yet an agreed definition of what it is.
Nevertheless, after several centuries of research, more than a dozen formal theories proposing reasons for dreaming have been proposed - including :
Some are complementary, others conflicting. None has been generally accepted.
See Wikipedia
Until fairly recently, dreaming was thought to be a uniquely mammalian activity - but recent research has identitified phenomena which appear to be dream-like states in several invertebrate species. E,g, spiders and octopuses
Further info on dreaming :International Association for the Study of Dreams
Also see Sleepplugin-autotooltip__plain plugin-autotooltip_bigSleep
"The purposes and mechanisms of sleep are only partially clear and are the subject of intense research"
Source Wikipedia"
Although extensive research in humans and animals has shown unequivocally that sleep is essential, the reasons why it's required are as yet unknown. Long term sleep deprivation not only severely impairs cognitive and motor skills, it's now been shown that it can cause physical damage to brain structure - and, in extreme cases, irreversible damage.
Note: Freudian and other 'psychoanalytic' theories of dreaming have not been included in the above list due to the lack of any scientific validation.