I'd liken it to an artist's sketchbook. If every piece is required to have the appearance of a master work, lest you be judged by it, then the sketches must remain private or else be destroyed (which they often were). But the masterpieces don't jump to the canvas without sketches. Forgo one, forgo the other. And an artist's sketches often have an elegance that's lost in the translation to a finished piece. I see similar parallels in the rough line art for animation, and certainly in an architect's studies. Not all of it is destined to be finished, either, but such work is often prized regardless.
So why (aside from fearing for our careers) should we be afraid to share?
Some code is inherently low-stakes. Some code will only ever be useful, even to the public, for a few months. Sometimes I just want to express an idea, where the proof of concept matters far more than making something shippable, which might imply strapping it down to a particular platform or ecosystem where no one outside those walls is likely to see it.
Even on the job, there's a time and place for the quick & dirty script, where anything more would be an over-engineered waste of time.
Back to the artist analogy, the best advice for maintaining a good portfolio is edit, edit, edit. Constantly be looking to remove work, leaving only your best, as you'll be judged by the worst. Does that model really work for GitHub? If everyone started withdrawing work they were no longer satisfied with, we'd all be worse off, if not actively harmed. So that's where I believe my artist analogy ought to end.