Bad dreams or nightmares generally happen at the end of the night, when the body is still asleep but in the REM (rapid eye movement) phase of sleep when brain activity is high. This is when dreams take place.
Clearing out tension and conflict
Children's brains and psyches are still growing, and despite their terrifying aspects, nightmares do have some use to them. They allow children to clear out tension and conflict that has occurred during the day, or to play out problems which they are dealing with at a given moment. For example, according to the Oedipus complex, when the child dreams of his mother or father (depending on whether the child is a girl or boy) being eaten by a large beast, this is a symbolic expression of the child's desire to see the 'rival' parent disappear.
Bad dreams also express guilt which derives from feelings, negative thoughts (jealousy towards a younger brother, anger towards a parent), or anguish about being abandoned, one of the most common fears experienced by children.
But it's also through nightmares that the child understands difficult life lessons like walking, language, first days at school, etc. During such times children can encounter nightmare periods which are nothing for you to worry about.