When a circuit is run (something is wired), the wire always starts and ends from plug, splice box, breaker panel, appliance
or basically from a location where the connection is contained and protected.
For instance, if you're running a wire for an outlet.
It may start from another outlet (power source) and continues through the wall to the other location.
At this point, it goes into a box (splice box) where it is connected to a device (receptacle, switch, GFCI, etc).
It never just goes to the device, without first going into a box. The purpose of this box is to contain any kind of spark or fire from a fault in the wire or device.
In other words, if something goes wrong, you don't want the spark
or fire to be out in the open, but rather contained within a box.
Some of these boxes are single gang (contains only one device), or multi-gang (contain more than one device).
They can be installed by being nailed onto the stud (wood frame) or it can be cut into the drywall or installed on the surface.
A professional electrician will know what type of box to use based on the intended use and location. Plastic boxes are becoming more popular, especially for residential work because they aren't conductive, come in multiple gang, can be nail-on or cut-in, and do not need to be grounded.