In the beginning of firearms, they were simply bare metal which rusted.
In an attempt to protect the metal better, browning was developed, which was not much more than rust that was smooth and formed a somewhat protective coating.
In the early 1800's a controlled form of rust was developed that was a blue color instead of brown, and offered more protection and was faster to apply.
There are a good number of methods of bluing metal, some more protective than others.
Prior to WWII a new form of bluing using hot corrosive salts was developed that allowed faster more durable bluing of guns and that's what's used today.
Modern hot salts bluing is a more blue-black in color, is fast to process, and offers reasonable protection, although it rusts rather easily and wears off from handling.
Today bluing is used mostly because it's a traditional gun coating that's an attractive finish.
There are much better gun coatings available, like hard chrome, the various epoxy based "paint" types, ceramic based paints, and polymer coatings, among others.
In early WWII the French, Belgians, and British discovered that a baked-on coating of enamel paint was a surprisingly durable gun finish and they used it for rifles, submachine guns and machine guns. Some pistols were also given paint or black colored lacquer finishes.
Today, there are a number of different paints that are very durable and wear resistant including the epoxy paints like Lauer Duracoat and epoxy paints with a ceramic additive. Many of these are more durable and more rust resistant than gun bluing.
Again, these days guns that are blued are mostly done because of the traditional appearance, and low cost per unit.