Due to fear of cancellation, the producers of Scrubs created an "emergency" ending in which the janitor was a figment of JD’s imagination.

Remember a few months ago when we told you that Scrubs was the most realistic medical series on TV? Well, the show’s original ending may have made that fact even harder to believe! Throughout the first season, the cast and crew (especially writer/creator Bill Lawrence) were almost sure that the show would be cancelled by the end of the season. So, the producers created an emergency plot twist that they could use when they’d have a forced series finale. 

Now, in season 1, the Janitor (Neil Flynn’s character) never directly spoke or was spoken to by any characters other than JD (Zach Braff’s character). Therefore, the idea was that the janitor would have been revealed to be a figment of JD’s imagination. This idea was kept into the second season until Flynn asked Lawrence if his character could finally interact with another characters in the series. There were however, a few glitches with the alternate ending. For one thing, in the 6th episode, Elliot throws a cup at the Janitor and says “Sorry!” and in the 11th episode, he gets punched on the balls by a little girl. 

(Source)