It happens when you do nothing more than quickly shut off a faucet.
BANG! It sounds like a shock wave just went through your pipes! You may even see faucets and other plumbing fixtures vibrate when this happens–that's how forceful the impact is. The phenomenon is called "water hammer" for good reason (technically, it is known as "hydraulic shock"). The shock wave that created the water hammer is traveling at thousands of feet per second and exerts pressures at hundreds of pounds per inch.
Water hammer can damage your plumbing system.
What Causes Water Hammer
Water Hammer (hydraulic shock) is by far the loudest and most common plumbing noise problem in the home. You are most likely to hear it in a home that has high water flow rates (around 10 feet per second) when a faucet or water valve is shut off quickly. The sudden halt to the flow of water literally causes the pipes to bang against each other and against framing members in the house.
Older homes have (or should have) a pipe fitting called an "air chamber" located on each hot and cold water line at or near each faucet or water inlet valve. This is rarely visible, except in unfinished spaces such as a utility room. Otherwise, they will be hidden behind walls along with the other plumbing pipes. The purpose of the air chamber is to act as a shock absorber for water when it is flowing at high speed under pressure. Since air compresses (it's a vapor) and water doesn't, the air chamber provides the water a place to temporarily expand into and thus softens the blow of the water shock wave when the faucet is turned off quickly.
Air chambers are often fabricated on-site by the plumber and installed at the faucet's water supply. They typically consist of a vertical length of capped pipe about 12" long or longer and are the same diameter as the water supply pipe. The problem with these makeshift air chambers is that they are sometimes made too short and undersized and eventually fill up with water, eliminating your shock absorbers.
The result? Water hammer.
How to Fix Water Hammer
If you have a water-filled air chamber, it is a relatively easy fix to drain the pipes, thereby restoring the air in the chambers and recharging the plumbing system.
A better long-term solution for eliminating the problem is to have a mechanical or engineered water hammer arrestor installed. These mechanical plumbing devices are charged with air or gas and will not fail as do typical air chambers.
The ultimate solution? Design the water supply system properly in the first place with larger-diameter supply lines. Larger supply lines will slow down the flow rate to 5 feet per second or so, which normally will not cause water hammer, so that it has about a 5 feet per second water flow rate.