It's a merging of two traditions: the Celtic Samhain (pronounced "sawen") and the Catholic church's All Saint's Day.
Samhain is a Gaelic celebration dating back to at least the seventh century, marking the end of the "light" part of the year, and a beginning of the "dark" part. As part of the celebration, people would dress as the demons that dominated the cold seasons.
In the medieval times, beggars through much of Europe would go "souling," asking for food in exchange for praying for the dead during All Saint's Day.
Both holidays happened during the same time of the year, and as Christianity reached Scotland and Ireland, the traditions were combined. Children would go "guising," dressing up as demons and going door-to-door asking for treats. If no treats were given, they would play small pranks. One of the most common was removing the front gate and hanging it on a tree.
This tradition reached North America through immigrants from Ireland's great potato famine. It took hold in the Western United States and Canada, then being settled, and slowly spread east. The exchange of candy stalled during World War II due to sugar rationing, but in the late 1940's it would be referred to in national publications, eventually spreading the tradition nationwide.
The first use of the phrase "trick or treating" was from a newspaper published in Blackie, Alberta on November 4, 1927. Similar traditions in Britain have taken on the phrase "trick or treat" when costumed kiddies announce their presence.
Posted 1923 day ago