When an electric current flows through a metallic spring, the spring acts as a solenoid. The coils of the spring become electromagnets. According to Ampere's law, a current-carrying conductor produces a magnetic field. In a helical spring, the magnetic field lines are concentrated inside the coil, producing a magnetic force. This magnetic force causes the coils of the spring to attract each other, leading to compression. Additionally, the current in adjacent turns flows in the same direction, leading to a magnetic attraction between them.