NAT (Network Address Translation) is a method created to extend the life of IPv4. Without it, we would have completely run out of IPv4 addresses many years ago, instead of more recently, as has happened. Unfortunately, NAT breaks the IP model of end-to-end connectivity, where each device has a unique IP address.
NAT, at it core, simply translates either or both the source and destination addresses on IP packets to be different addresses. There are multiple variations of NAT. The common version used to allow devices on a network with private addresses use a single public address is call NAPT (Network Address Port Translation).
NAT can be used on different device types, but it is most convenient to to run a NAT process on a firewall or router that connects a private network to the public Internet. It is not a firewall or router requirement to run NAT, but that is usually the logical place to run it.
NAPT looks at the source layer-3 and layer-4 addresses of packets passing from inside to outside, then it creates or updates an entry in a NAT table and replaces the source layer-3 and layer-4 addresses with different addresses before forwarding the packets.
When a packet comes in from the outside with the layer-3 destination address of the NAT device, NAPT looks at the destination layer-3 and layer-4 addresses, and it looks up in the NAT table to determine which layer-3 and layer-4 address to use to replace the destination addresses, then it replaces those addresses and forwards the packets to the inside. NAT drops any packets for which there are NAT table entries.
NAT table entries will time out, or, in some cases with TCP, will be purged when the connection ends.
It important to NAPT to inspect both the source and destination addresses to create NAT table entries for a particular conversation. That helps to prevent outside hosts that are not part of the conversation from sending unwanted packets to the inside host.
Both the source and destination addresses on the packets must match the NAT table entries before packets are allowed from outside to inside. That means that only inside hosts can initiate a conversation because there is no NAT table entry in place for an outside host to initiate a conversation. This brings up the concept of port forwarding, which essentially create a permanent NAT table entry in order to allow outside hosts to initiate a conversation with an inside host.
For more information about NAT, you can look at RFC 3022, Traditional IP Network Address Translator (Traditional NAT).