Not all gases cool when expanded, it depends on the gas in question and the temperature over which the process occurs. Many gases have inversion temperatures, when warmer than a certain temperature the Joule-Thompson coefficient is negative and expansion causes them to warm, below this temperature and expansion causes them to cool. For air I think the inversion temperature is ~325C. Heating (or cooling) upon compression comes from the same effect, just in reverse.
The Joule-Thompson effect itself is a consequence of the internal energy of non-ideal gases. Ideal gases have a Joule-Thompson coefficient of zero and do not experience heating and cooling during isocaloric compression.