Styrofoam works well as an insulator because it mostly consists of air confined to small pockets. These pockets hinder the convection process from carrying heat energy away from (or to) the substance inside the container.
Three different processes allow heat energy to flow: radiation, convection and conduction. Of these, conduction and convection are the two processes relevant to the use of Styrofoam. Conduction involves the flow of heat energy from a hotter object to a colder one. For example, a person picking up an ice cube notices that the ice cube melts in his hand as heat conducts from his hand to the cube. Convection involves a series of currents that emerge when a gas or liquid flows from a warmer place to a cooler one, or vice versa.
Styrofoam is a poor conductor, and the air pockets trapped inside the material keep heat energy from leaving. This is why Styrofoam products are popular for holding hot things like cups of coffee. The material does not conduct the heat from the beverage through to the hand in the same way that a metal or glass cup might. However, the trapped air pockets limit convection of the heat away from the beverage, and so beverages stay hot for longer in Styrofoam.