The practice of wearing costumes or masks during this Autumn celebration comes from a Celtic Samuin tradition. During this celebration, young men impersonating evil spirits by dressing up in white costumes with blackened faces or masks. It was believed that during the transition from one year to the next, the realms of the living and the dead would overlap allowing the dead to roam the Earth again. By dressing up as spirits they were trying to fool actual spirits into thinking they were as well.
In the 8th century, the Catholic Church began “All Hallows Even (evening)”, “All Soul’s Day”, and “All Saints’ Day”. Many of the traditions of Samuin were then adapted into these festivities and by the 11th century, the Church had adapted the Celtic costume tradition to dressing up as saints, angels, or demons.
As for the trick or treating, or guising, traditions began in the Middle-Ages, children and sometimes poor adults would dress up in costumes and go door to door during Hallowmas begging for food or money in exchange for songs and prayers, often said on behalf of the dead. This was called “souling” and the children were called “soulers”.
Souling ultimately gave rise to guising in the 19th century, with children dressing up and begging for things like fruit and money. instead of prayers, a performance was offered to earn the treat.
The practice of guising made its way to North America, probably brought over by the Scottish and Irish in the late 19th or early 20th century.
Trick or treating instead of guising on Halloween began in the 1920s and 1930s, first in the western half of North America. WWII Sugar rations caused a stop to the practice but it resumed after the rations were lifted. Within five years trick or treating was a near ubiquitous practice throughout North America.
At this point, instead of performing for treats, the action transformed into extortion. Kids get a treat or you get a trick.