For resilience. Just as many Muggles indulge in the odd sugary snack, lots of our favourite wizarding world characters also turned to confectionary and cakes for the occasional pick-me-up. The most obvious example of this was the use of chocolate to diminish the impact of a Dementor.