In olden times, it was believed that during Samhain, the veil between our world and the spirit world was thinnest, and that the ghosts of the deceased could mingle with the living. The superstition was that the visiting ghosts could disguise themselves in human form, such as a beggar, and knock on your door during Samhain asking for money or food. If you turned them away empty-handed, you risked receiving the wrath of the spirit and being cursed or haunted.
Another Celtic myth was that dressing up as a ghoul would fool the evil spirits into thinking that you were one of them so that they would not try to take your soul. In the U.S., trick-or-treating became a customary Halloween tradition around the late 1950s, after it was brought over by Irish immigrants in the early 1900s.