Software is often extended by simply adding new features and code there, often intentionally or unintentionally with some flaws and without changing the "blue print" of the software (The architecture") before changing this.
This causes a phenomena called "technical debt" - what you saved by working quick and dirty initially makes you pay interest in maintenance or bigger risks and costs for future changes. Or what you didn't know then still costs you more than you expected. But you got wiser and now know how to make it better and less costly.
Somebody here once explained this great with building a medieval castle (We Europeans can grok this). See this fine example there:
Like those, there is never a real blue print or detailed specification. You add new turrets, flags, walls, etc around it as you need them, and the more you add this way, the bigger the risk that something will eventually collapse or catch fire. Like in the past, software development is also often done without fully understanding the consequences of the changes. The systems including users, hackers and politics are way too complex to predict everything for years in advance.
So, you refactor. In the castle, you tear down old structures and replace them by modern structures. Or you tear down old buildings to have room for a new one. When your enemies suddenly have cannons, you have to think about abandoning your castle or modernizing it as whole while defensive technology progresses (Like towards a star fortress).
In software, you remove old code that is no longer useful, unify code that does the same task, make interfaces follow newer standards etc. You check how requirements changed over time and what consequences that has now (eg, software was designed for 10 users, but now has to support 1000 users, and despite being so well designed that it ran fine even with 100 users, its now no longer fitting to the changed environment)
Refactoring is a paradox thing in practice. It is a VERY profitable thing in the long term (little risk, big gains), but something only few customers will pay. Quite contrary: One of my former customers actually wanted to make us pay damages to him for us not predicting 17 years in advance, how the requirements for the software changed.
EDIT: Another nice castle example is from my hometown:
The structure in the middle is the old keep, constructed in the 13th century. The surrounding structures had been added after the 16th centry, when the castle was converted into a palace over time.