A device includes a resistance switching layer, a capping layer, a top electrode, a first spacer, and a second spacer. The resistance switching layer is over a substrate. The capping layer is over the resistance switching layer. The top electrode is over the capping layer. The first spacer lines the resistance switching layer and the capping layer. The second spacer lines the first spacer. The capping layer is in contact with the top electrode, the first spacer, and the second spacer.