Dreaming is thought to mainly occur during our deep sleep cycles when brain activity is highest. This high activity occurs when the body inactive so I think that our dreams occur to give the brain stimulation, whether it be to process things that happened during the day or recall memories/emotions. I would assume that bad dreams are also part of this processing as your brain is trying to make sense of what was negative and the consequences of these feelings.
Comments