For starters, it secures the barrel to the upper receiver. The barrel indexing pin fits into the indentation in the upper receiver and the barrel nut threads over top of the barrel, onto the receiver, in order to keep the barrel affixed to the upper receiver.
Secondly, the barrel nut allows the handguard – whether free-floating or drop in – to attach to the upper receiver. After securing the barrel nut to the upper receiver, most free-floating handguards attach to the barrel nut via allen keys or a company-specific wrench.
Finally, in the case of direct impingement, the barrel nut holds the gas tube in place to allow the AR-15 to cycle properly. When a bullet is fired from the AR, the gas forcing the bullet down the barrel is pushed through the gas port, through the gas block, down the gas tube (which is secured to the upper receiver by the barrel nut) and helps to cycle the next round