Nuts are a type of fasteners with a threaded hole. These are almost always used in conjunction with a mating bolt to fasten multiple parts together. The two partners are kept together by a combination of their threads’ friction, a slight stretching of the bolt, and compression of the parts being held together.
In applications where vibration or rotation may work a nut loose, various locking mechanisms may be employed: lock washers, jam nuts, specialist adhesive thread-locking fluid (Loctite), safety pins (split pins) or lock wire in conjunction with castellated nuts, nylon inserts (nyloc nut), or slightly oval-shaped threads.
Square nuts, as well as bolt heads, were the first shape made and were the most common, largely because they were much easier to manufacture, especially by hand.
While rare today due to the reasons stated below for the preference for hexagonal nuts, they are occasionally used in some situations when a maximum amount of torque and grip is required for a given size: the greater the length of each side allows a spanner to be applied with a larger surface area and more leverage at the nut.
The most popular shape today is hexagonal, for similar reasons as the bolt head: six sides give a good granularity of angles for a tool to approach from (good in tight spots), but more (and smaller) corners would be vulnerable to being rounded off. It takes only one-sixth of a rotation to obtain the next side of the hexagon and the grip is optimal.