How many times have you heard something along the lines of this? Our heroes are in a tough spot! Whatever will they do? But wait! Our hero is going to harness the POWER OF FRIENDSHIP and gain powers they didn’t have before! Or a convenient army arrives and saves them. Or their enemies that are on the verge of raising the DARK LORD have to take a convenient lunch break.
These kinds of convenient happenings are known as deus ex machinas, meaning "god from the machine." It is called that because in a Greek plays, a guy dressed as a literal god would be lowered down onto the stage using a machine, and neatly wrap everything up. A deus ex machina usually happens when an author writes himself or herself into a corner.
As the comic above illustrates, deus ex machina used badly can make a story’s conclusion somewhat unsatisfying, as it makes the conclusion feel unearned. For an example, I’ll write a quick fantasy story to illustrate my point.
Our hero, Sebastian, is on an epic quest to save the world. He has fought his way through hordes of orcs, kobolds, and other such vicious monstrosities to stop the demonic ritual of the evil dark lord, Mordrath the Accursed. When Sebastian faces Mordrath, the foul demon is too powerful, and Sebastian simply cannot defeat him. As Mordrath raises his sword to perform the killing blow, however, he suddenly comes down with the flu and has to take a break.
This kind of ending is unsatisfying, because no one earned anything. You, the reader, get no proper conclusion to the conflict. No one loses anything, and no one gains anything. The characters don’t get any development. This deus ex machina is an example of lazy or badly planned writing.
However, we can rewrite this conclusion to make it more satisfying. Perhaps, before the fight, Sebastian coated his blade with venom to incapacitate Mordrath. Or, maybe he intentionally sent plague-infected rats into the dark lord’s castle to give him a disease. These examples establish Sebastian as a clever fighter who identifies his enemies’ weaknesses. It also makes it so that his salvation is earned, and not just a coincidence.
Avoiding a Deus Ex Machina
In my experience, the best way to avoid a deus ex machina is to plan out your writing. If you start writing without a plan, you may find yourself being trapped in a corner. Maybe the evil mad scientist destroyed all of reality. Maybe your hero got his spine ripped out and got buried alive, but you still want him to win. Both of these situations warrant a deus ex machina. The best way to avoid these dilemmas is to plan ahead. Figure out the climax and denouement beforehand. As long as you pay attention to these things, you can avoid writing a deus ex machina in the future.