While the modern tradition of trick-or-treating is focused on giving children candy for no apparent reason, it is in fact based on an earlier tradition from European Catholics.
November 2 is known in the Catholic Church as "All Souls Day," and is dedicated to praying for the souls in purgatory. On this day Catholics pray for their deceased relatives and friends, often visiting cemeteries to remember those who are no longer on this earth.
It is with this celebration that many local traditions were created and became mingled with the festivities of All Hallows’ Eve when immigrants started establishing themselves in the United States.
Souling
In various cultures in Europe there developed a tradition of “souling” and baking “soul cakes” in honor of the faithful departed. These cakes were baked on All Hallows’ Eve (October 31) and children would go out on All Saints Day and All Souls Day, begging door-to-door for these cakes in exchange for praying for deceased relatives and friends.
Eventually this tradition was morphed in America with other customs, and after candy manufacturers caught wind of it, the holiday was monetized and developed into what it is today.
As in so many other cases, the religious origins have turned into something quite different and trick-or-treating is now entirely removed from praying for the deceased.