As you’re sifting through your Halloween bounty this year, consider all the forms candy can come in. Some will be smooth and chewy, such as caramel. You’ll surely have some gummy animals in the mix, along with a rainbow of lollipops. All of these desserts can be made with the same main ingredient: sugar. It’s through the wonders of chemistry that confectioners make the sweet stuff take so many different forms.

“Basically, candymaking is about controlling the size and shape of sugar crystals,” says Alton Brown, creator of the TV shows “Good Eats” and “Good Eats: Reloaded.”

Each grain of table sugar is a crystal — a tidy structure made of molecules called sucrose. Units of sucrose like to stick to their neighbors, which keeps each little chunk in a neat shape. But when sugar gets wet, some of those bits of sucrose want to attach to water molecules instead. This makes them lose their crystal structure and dissolve. Hot water can dissolve more sugar than cold water, so a cooked-up syrup will start to form crystals as soon as it cools back down. That’s how many candies are made.

Candy texture is determined by the size and number of sugar crystals, which chefs can control by the speed and method they use to cool that sweet syrup down. The biggest crystals make rock candy: You can do this at home by dropping a string or stick into a glass of sugar syrup and letting it cool down slowly — by sitting at room temperature, undisturbed, for days. With no movement to keep sucrose molecules from clustering together, the sugar will form bunches of giant crystals on the string or stick over time.

On the other end of the sweet spectrum are confections with no crystals at all. Glass candy — such as a lollipop — is made by cooling syrup down so fast that sucrose molecules clump together randomly instead of forming the usual crystal structure. Adding gelatin during that process produces gummies and marshmallows. Cotton candy is made up of tiny threads of this glass, which machines create by heating sugar and then shooting it through tiny holes as it cools.

Chewy, fudgy treats are somewhere in the middle: You want crystals to form, but you want lots of tiny ones instead of a few giant, rock-candy-style chunks. Chefs achieve this by gently cooling their sweet syrup while also stirring it continuously.

“I think that in general, people don’t really realize how much texture affects our perception of taste when it comes to candy,” Brown says. “Honestly, whether it’s fudge, brittle, toffee, taffy . . . texture is probably about 70 percent of what we’re sensing when we enjoy it.”