Sleep is still poorly understood, it's a confusing landscape of processes which keep us alive, and working well in the world. One of the stranger aspects of sleep is dreaming, a period of vivid hallucinations which can be a great or terrifying experience.
Like so much about sleep we don't know exactly why we dream or how, despite decades of sleep studies. We do know that we tend to dream the most and the most vividly during the REM stage of sleep; the scientific community is also pretty certain that everybody experiences dreaming, although the amount remembered varies individual to individual.
The question of function is the most interesting, and there have been multiple thories put forward to why we dream. One of the most popular theories is that dreaming works as a tool to help our minds process all the information and stimuli which we have encountered over the course of the day. Our brains are bombarded with hundreds of thousands of external and internal stimuli every day; filtering and prioritising what is passed onto out concious thought, and tucking away information into our subconcious which we are never conciously aware of. When we sleep the amount of external stimuli is decreased dramatically which allow our bodies to focus on reinforcing learning, filtering though the stored information for the day and processing everything it has not had the resources to during the waking hours, and dismissing everything from storage which is deemed to have no further function. Some researchers believe dreaming is thought to be a component in this process.
This theory is not just speculation, during studies the participants who were tasked with more learning in their waking hours had increased dreams during their sleep. Participants in a dream study whor were taking a language course showed increased dream activity than those who were not. These studies have bolstered the confidence in this theory and have helped it to become more popular in recent years.
Another theory is that dreams are a way of processing our emotions; helping us to gain a better of our interaction with the world and how we can best navigate through it. During the day we are often acting to achieve a task, navigating through our environment effectively, this puts our brain's focus on the superficial and leaves little available to form deeper looser connections between more abstract thoughts. When we are asleep more processing ability is available for our brains to explore these abstract connections which helps us to form new ideas annd deal with the emotions which have been raised during the day.
The least interesting theory is that dreams serve no function, they're simple a side effect of other functions of our brain, and the random firings of elements of our brain causes the hallucinations we experience as dreams. No matter which theory you find the most interesting, until we find a better way to decode the mysteries of our grey matter it's all just theory!