Most electrical boxes are attached to a stud before the drywall is even installed. When you add a new box to an old wall, we always try to put it in right next to a stud for solid attachment. Specialized hardware does exist to allow putting an electrical outlet or switch absolutely anywhere without reference to a stud.
Looking at most of them on the store shelves you can be at a loss trying to understand how to make them work. Here you see the details, on both sides of the wall.
When putting thick wall coverings over existing walls, like another layer of drywall or foam insulation, extender sleeves keep the wires properly protected without moving the existing box.
For still photos of all of this click here.
Learning Curve 62