A bayonet turns a rifle into a spear.
Spears have been used for at least four hundred thousand years. Some of the various monkeys use spears too.
While a pointy stick is not the worlds best fighting weapon, it works, and it kills. The Romans knew that it was the penetrating wound from the Gladius that killed quickly. The spear provides a low cost, easy to train, penetrating weapon. This caused the spear to be the most common weapon until the advent of the firearm. And so even after the widespread use of the firearm, people kept the ability to use the firearm as a spear.
Some would foolish argue that the firearm also doubles as a club, and that this club is a fine weapon in it self rendering the bayonet unnecessary. Those people do not know their history.
While a rifle does make a functional club, it is not the buttstoke that often kills. I have buttstroked several people. It is good for distracting, injuring, or forcing compliance. However in the military fighting setting the buttstroke was ment to be create the opening to bayonet the enemy.
The bayonet is obsolete, modern warfare doesn't need it. However fighting with spear like weapons is just as effective as it was 400,000 years ago.