The cash the dealer gives you gets him a used gun. He must then put it out and resell it to make a profit. Meanwhile, his cash is tied up and you may walk with your cash.
The higher trade value is because you then buy something from him. He makes money on both the used gun you traded and the new one you bought. He is willing to give you a higher trade allowance because he makes money on two transactions instead of one. In addition, he ties up less of his cash. Essentially, he makes slightly less per transaction, and is sharing a bit of the profit with you.
This is why stores like WalMart want to give you a gift card instead of cash if you return something without a receipt. You then buy something else with the money in store, and they make a profit on it.
Furthermore, I believe you pay sales tax on the net difference, which makes a trade even better for you.