There are two reasons to wear sunglasses. The first reason is if you don't like the bright sun shining in your eyes, as the dark surface of the sunglasses helps to block out bright light and make the world appear darker. The second is that the sun's ultraviolet rays can be harmful in the long term, causing all sorts of problems with your eyes including loss of eyesight and eye cancer. Good sunglasses protect against this, as their lenses filter out most of the harmful UV rays.
So how do sunglasses work? The darkening effect is a very simple one: looking at the world through tinted lenses makes it seem darker to you - even though the effect is really just an optical illusion, it can help you if exposure to bright sunlight tends to give you a headache or cause you to squint.
The UV-filtering effect, however, is more complex. UV-filtering lenses are coated with special chemicals that allow light to pass through them, but reflect away UV. UV rays are basically high-frequency light waves, which means that the chemical structure has to be built to deflect higher frequency light while allowing through lower frequency light. This is difficult science, and the materials needed to do it are expensive.
The most complicated sunglasses of all are prescription sunglasses. These are sunglasses that not only protect from light and UV, but also work like normal glasses to correct your eyesight. For this to work, it requires that normal vision-correction glasses are taken, tinted and coated with UV-reflecting chemicals - a complicated three-step process. However, all the ingredients work together flawlessly, to produce sunglasses that are wearable by people who need their vision corrected all the time. It is even possible to buy clear tinted lenses that fit over the top of your normal glasses, effectively a do-it-yourself way of making prescription sunglasses.