Refactoring is the process of editing code to improve efficiency and readability without changing the output. I made a little example to demonstrate how a beginner can start refactoring their code. This mini-tutorial covers the DRY (Don’t Repeat Yourself) concept, and might come in handy in the future.

Let’s say I have some data in the form of a JavaScript/JSON object or array. The data and how it’s formatted doesn’t matter much here, it could be much more complex, but I’m leaving it simple for example’s sake. (It could come from an API, but I’m going to leave out the step of fetching data for this example as it’s irrelevant.) Here’s our data:

Data

var sessions = {
  mobile: [1, 2, 3],
  tablet: [3, 4, 5],
  desktop: [6, 7, 8],
}

Now let’s say I have a function that I need to run that data through multiple times. Maybe I’m sending it through an API to map out a chart. In this case, I’m printing the data to a website (the DOM).

Function

function printData(id, name, sessions) {
  var div = document.createElement('div')
  div.id = id
  div.textContent = name + ' : ' + sessions
  document.querySelector('body').appendChild(div)
}

#javascript #fundamentals

Basic Refactoring: Don't Repeat Yourself
1.20 GEEK