The Sorting Hat places each new generation of Hogwarts first-year students into the four Hogwarts Houses. The Sorting Hat moves through your mind to decide if your primary characteristics are courage (Gryffindor), ambition (Slytherin), hard work and fair play (Hufflepuff), or intellect (Ravenclaw). So the Sorting Hat represents one quick way of characterizing all the Hogwarts students we ever meet: if you're a Ravenclaw, you're smart, if you're a Hufflepuff, you're patient, etc.
When an interviewer asked Rowling point blank, "Has the Sorting Hat ever been wrong?" Rowling said simply, "No" (source). We sort of can't imagine how that's possible – don't people ever change or outgrow their houses? – but we guess that's the point: it's magic.
J.K. Rowling has also confirmed that, when the Sorting Hat speaks to Hogwarts students, its words come "from the founders themselves" (source). So the Sorting Hat is the voice of Hogwarts; it is intimately tied to Hogwarts' history and origins. At the same time, the fact that the Sorting Hat is never wrong about people troubles us a bit, since weren't the founders of Hogwarts ever wrong? What about that whole Slytherin-versus-all-the-other-founders argument? Doesn't that cast doubt on the people who created the Sorting Hat in the first place?