I wear a hat outside. It makes walking in the Seattle rain quite pleasant, as my glasses don't fog up and the water doesn't go down the back of my neck. When sunny, I don't need to apply sunscreen, and the glare from the top of my head does not cause car crashes.
As a bonus, I can imagine myself as Clint Eastwood.
People were spending much more time outside and the roads were much more dusty. You need a hat to keep yourself from the sun and the dust. Cars made them obsolete.
They also make it way easier to great people even over some distance, without awkwardly moving your hand in the air or shouting and annoying all the others.
Men wearing hats is still quite common today. But the style has changed to baseball caps and similar forms. Most of those "dress codes" usually also have a more practical origin. So it's less of a code, and more a practical benefit.
If you are interested in this topic, especially from the US perspective, I recommend this book: https://www.alibris.com/Hatless-Jack-The-President-the-Fedor... . There was apparently significant social pressure for all men to wear hats until the mid C 20th.