“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 more than a dozen formal theories proposing reasons for dreaming have been proposed after several centuries of research. Some are complementary, others conflicting. None has been generally accepted.
Further info International Association for the Study of Dreams
Note: This item should not be confused with the concept of dream interpretation - which goes back for millennia, and has little, if any, scientific basis.