In a single line of notes - one voice, it's only to tidy up the presentation. Notes which are on the middle line and above generally have stems down, notes below, stems up. In your example, the first is slightly easier to read. There's also the thought that in 4/4 and 6/8, bars could be split in half, again easier to read, so if, for example,(4/4) there was a dotted crotchet followed by another dotted crotchet, it's easier to read as a dotted crotchet followed by a quaver tied to a crotchet. Some disagree, but that's how it used to be done. Now, things are more lax.
Grouping of similar notes tidy up too. With 8 quavers in 4/4, they look better as 2 groups of 4. With multiples, there's no need to write singles as in your second example, although if they had words, and a phrase ended on ,say, the 3rd quaver, it's not bad to separate that to help show phrasing.
Other answers have already mentioned different voices, satb for instance being stem specific - s treble clef up, a treble clef down, t bass clef up, b bass clef down.