Whenever you splice wires together while installing residential circuitry, the electrical code requires you to enclose the connections in a junction box. This safety measure prevents fires that can occur when the wires overheat and also protects people from getting shocked by live wires. You don't often have to install a dedicated junction box, however, because switches, lights and receptacles are all installed in electrical boxes that can serve double-duty as enclosures for spliced wires.
The electrical code requires wire connections to be enclosed primarily because loose connections present a fire hazard. Even if you securely twist the wires together, screw on a wire cap and wrap the ends with electrical tape, there is still a possibility that current surges can overheat the wires. Over time, this may degrade the tape and wire caps, and insulation or framing may ignite. This degradation can also result in exposed wires, and even if they aren't accessible enough to touch, you can still be electrocuted by driving a nail or a screw into the wall.
Electrical Boxes and Junction Boxes
Installing an electrical box is a precursor to adding any device, like a switch or receptacle, to a circuit. Boxes can be made of metal or plastic, and you usually screw or nail them to a stud or rafter, although you can anchor remodeling boxes directly to the surface of drywall. The only difference between a box for a circuit device and a junction box, or J-box, is that the latter serves no other purpose than to enclose spliced wires. Its opening is covered, not by a circuit device, but by a flat metal cover.
The Need for a Junction Box
Electricians usually minimize the number of junction boxes needed for wiring. They plan the circuitry so that they can make connections for branch circuits inside a switch or receptacle box, using a box big enough to accommodate all the wires. Careful planning usually eliminates the need for a separate J-box when wiring a room from scratch, but one or more may be necessary when adding to existing wiring. A J-box may also become necessary in other circumstances, such as when a miscalculation results in the need for splicing because of a cable that is too short to reach its destination.
Installing Junction Boxes
When upgrading the wiring for a room, you may find it necessary to tap into a wire to add a branch circuit for a light or outlet. You'll need a junction box if you can't make the connections inside an existing electrical box. You should install the box with the opening facing out from the wall so all the wires inside are accessible. Like any electrical box, it should be installed so that the edge of the opening is flush with the wall. Screw the cover on with machine screws so you can remove it easily.