No one really knows why we yawn, maybe it has some useful purpose - it does allow us to take in more oxygen and expel carbon dioxide, it also increases heart rate a bit. Yawning could keep the brain aroused in situations where sleep is unwanted - like first period maths lessons or 9 am meetings.
Why we yawn when we see others yawning has baffled scientists for ages and a number of suggestions have been put forward to explain this phenomenon. What we do know is that yawning is an involuntary action - our brain does it without us thinking about it. Even very young babies yawn, showing that it's a built in action (chimps do it too by the way). Just thinking about yawning can trigger the bit of the brain that causes a yawn and, chances are when reading this you will end up yawning at least once!
My favorite explanation for why we yawn when we see others yawn is that it's a throw back to the days of our ancestors when we lived in groups. Yawning could have been a sign that it was time for the group to go to sleep or change activities. It's important, after all, that all group members were ready to do the same thing at the same time.
It appears that there is some relationship between yawning and our ability to 'put ourselves in other peoples shoes'. Not all people can 'catch' a yawn when they see someone else yawning and these people also appear to be less able to understand things from other people's points of view. This is an important skill for being able to get along with others - it lets you sympathize with them and understand how they feel. So yawning is maybe just a by-product of us being able to use our own experience to understand how others are feeling. Maybe it's due to accidental 'cross-wiring' in the brain that occurs when the 'thinking about others' part of the brain is stimulated.
Another theory is that yawning is a way of baring our teeth at potential enemies - something along the lines of "I may be sleepy but you'd be stupid to attack me, just look at my vicious teeth!". Could it be that the reason a yawn is contagious is that a whole group of sleepy primates showing teeth together is less likely to be the target of a predator?