DEV Community 👩‍💻👨‍💻

Arnold Ho
Arnold Ho

Posted on

Refactoring ELI5

Disclaimer: I am not an expert, I am merely learning in public. If I got something wrong or left out important details, please leave a comment! ❤️

Alrighty, lets go!

Refactoring a piece of code changes the structure of your existing code without altering what it does. Take a look at the following javascript example:

if(weather === 'rainy') {
  console.log('bring an umbrella')
} else {
  console.log('no need umbrella')
}
Enter fullscreen mode Exit fullscreen mode

In the code above, I passed the variable weather into the conditional function, if its rainy, the code will tell me to bring an umbrella.

This code is fine, but we can do everything in a much simpler way with the following:

console.log(weather === 'rainy'? 'bring an umbrella': 'no need umbrella')
Enter fullscreen mode Exit fullscreen mode

In the second code, I have turned the if else statement into a ternary operator wrapped around by a console.log. The two codes do exactly the same thing but the second one is just a lot simpler to look at.

We refactor our codes because of a few things (non exhaustive list):

  • Improve our code readability (Imagine extending the above idea into a huge file with many lines)
  • Improve efficiency of our code, making it easier to work with
  • You can refactor a code such that features can be re-used elsewhere

Happy coding!

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post