Earworms
Earworms are fragments of a known musical item which replay repeatedly inside one's head.
They do not serve any obvious useful purpose.
The Analogy between Musical Items and Languages
One consequence of the Daydream hypothesis is that music is a mutated copy of part of our language learning instinct.
In attempting to define a precise analogy between language and music, there is reason to suppose that each musical item is analogous to one language, where each musical "language" has a very constrained syntax, so constrained that there is only one valid utterance, ie that particular musical item.
Given this analogy, the repetition of one musical item over and over again in the imagination is equivalent to the repetition of valid utterances of the first language that an infant is learning.
In the case of learning a real language, the set of possible valid utterances is much larger than one, and the imagining of different utterances is equivalent to practicing the generation of valid utterances in the language being learnt.
There is no direct evidence that such a process of imagining valid utterances in a first language actually occurs. But if such a thing did occur, it is quite likely that we would not remember it later on as adults (or even as older children), just like we forget most or all of our infant experiences by the time we are old enough to communicate our memories of our experiences to other people.
(Also, when we attempt to learn a new language at some later stage of life, after we have already learned our first language, the language learning instincts which are designed to accelerate the process of learning the infant's primary language have faded away – because they would be a distraction from all the other things that adults and older children have to deal with. So there may be various phenomena that are part of the initial language learning process which will never be subjectively experienced by those learning a second language later in life.)
If indeed such internal practicing of valid utterances does occur during the learning of a first language, then musical earworms are a side-effect of two things: that speech gets internally practiced, and that music has evolved as a mutated form of part of the speech learning instinct.
And we can come to the conclusion, which is perhaps not very surprising, that earworms serve no useful purpose of any kind.