The brain is an incredibly complex system - around 80 billion neurons with trillions of connections between them. When such a complex system is 'idling', not occupied with important everyday matters of survival, it can 'freewheel', in various ways - making plans, combining ideas in new ways, reminiscing, daydreaming, being creative, and releasing tensions by being silly (which may also be a means of social bonding using humour, derived from early play).
This appears to be more than just a side-effect of not being specifically occupied - there is a whole neural system that becomes active when this kind of activity is going on, the
Default Mode Network. This suggests that these things play an important role in our success as a species.