1. Back up your data
Before you do anything, you want to make sure you aren't going to lose your data, so be sure to back up your gadget. You can do this through iCloud or iTunes.
To back up with iCloud, get on a Wi-Fi network and go to Settings >> iCloud >> Backup. Turn on iCloud Backup and then tap Back Up Now. After the backup is done, go to Settings >> iCloud >> Storage >> Manage Storage to make sure it really did back up.
To back up to iTunes on your computer, plug your gadget into your computer. Open iTunes and go to Files >> Devices >> Transfer Purchases. This will save any purchases you made directly on your gadget.
Then go to File >> Devices >> Backup and select "This computer" and click "Back Up Now."
Once your backup is complete, you want to disconnect your gadget from iCloud so the next owner can't get into your data. To do this, go to Settings >> iCloud and tap Sign Out at the bottom of the screen. You'll need to tap Sign Out one more time, then tap Delete from My iPhone. It will ask for your password.
If you have an older gadget running iOS 7 or earlier, in Settings >> iCloud you'll need to tap Delete Account.
2. Delete your data
Once you're disconnected, it's time to get rid of your content.
Go to Settings >> General >> Reset >> Erase All Content and Settings. This will wipe out everything on your phone.
Depending on your settings, you might have to enter your Apple ID and password, your device passcode or your Restrictions passcode. Once that's done, tap Erase and wait a few minutes for it to finish.
Take a quick glance through the gadget to make sure everything is really gone. Then you're ready to sell or give it away.
If you've already sold or given away the gadget and realized you didn't wipe it, don't panic. Go to icloud.com/find, select your gadget and choose Erase. Then select Remove from Account.
If you aren't using iCloud with your gadget, then things are a bit more complicated. You'll want to contact the new owner and have them do a full reset using the instructions above.
Apple Pay users will want to go into the iCloud Apple Pay settings and make sure the old gadget is removed from the list of approved gadgets. You don't want the new person charging groceries to your cards, after all.