“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.
(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.)