Well, first of all what is yawning? When you yawn, you are inhaling air and at the same time you are stretching your eardrums. This is why you sometimes pop your ears while you yawn. Furthermore, if you yawn and at the same time stretch your body, that is called pandiculation. Now, why do we yawn? Well, the researches think that their are many reasons and the first one relates to how cool you are. When you are tired or exhausted, your brain temperature will increase, just like when computers heat up after being used a long time. The oxygen that you breathe in when you yawn will help cool down your facial blood, which unsurprisingly, helps cool down your brain.
Another reason why we yawn ties up with you stretching while you do it. When you pandiculate, you strech out your muscles and cool down your brain, allowing your brain to be more alert and your muscles ready to react a moments notice. This is why yawning being contagious makes sense. For example, let us say we have a herd of gazelles grazing in some tall grass. The first gazelle to yawn will serve as a reminder to the rest of the group to stay alert. This is one of the reasons yawning is contagious. Yawning being contagious helps the herd stay alert and ready to act a moment's notice.
(FYI these are gazelles)