Evidence suggests that Bach completed and revised the Fantasia and Fugue in G minor for organ as an audition for an organist position in Hamburg in 1720. He didn't get the job, but, happily enough, posterity did get the piece; generations of organists since then have considered it one of their repertoire's crown jewels. The two parts of BWV 542 (the Fantasia -- sometimes titled Prelude instead -- and the fugue) are thought to have been composed separately: the fugue is assigned Bach'sWeimar years (1708-1717) and the fantasia to his time in Cöthen (1717-1723, but, if the audition theory is correct, not later than 1720).
The fantasia opens spaciously and in recitative-like style, but as it unfolds Bach finds room for dense passages in upper-voice imitation. There are five more or less balanced sections to this fantasy; intensely dramatic sections are interwoven with quieter, more even passages. The wide tonal scope of the Fantasia has been a subject of fascination for two centuries of musicians: just when some kind of harmonic stability seems to arrive, Bach shoots off on a mock-improvised cadenza that jolts the music into a whole new pitch realm. Thus the Fantasia both lives up to its name and contains quite a bit of contrapuntal rigor, and then, on top of that, more than one worthy mind has deemed the fugue to be Bach's ultimate accomplishment in the field of organ counterpoint. The task of selecting a king from that noble crowd, however, is not an enviable one. Though it provides the sense of a stable answer to the fantasia in its predominantly even sixteenth note rhythms, it is similarly ambitious harmonically: Bach makes two revolutions through the entire circle of fifths. The fugue makes a fine contrast with the later music of the fantasia while nevertheless seeming of a piece with it.
The Fantasia and Fuge were put together for the first time in Griepenkerl's Bach Edition of 1844. Up to that date they were known as separate pieces.