Skip to the content

Refactoring

JavaScript · Unit 19: Clean code

Refactoring means changing how code is written without changing what it does. If the result changes, you didn't refactor: you broke something.

The two lines below print the same thing; one keeps the rule in a single place.

function pay(bill) {
  return bill + bill / 10;
}
console.log(pay(200));
console.log(200 + 200 / 10);

Prints

220
220

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Find the bug

    Shipping is free from 500 up and both purchases are 600, so both should print 600. Which line has the error?

  3. 3. Complete the code

    Fill in the blank to also charge the 400 pair of pants with its tax.

  4. 4. Put the lines in order

    Put allWithTax(prices) in order: a new array with each price plus its 10%.

  5. 5. Complete the code

    Fill in passed, which returns true if the score reaches 6.

  6. 6. Find the case that fails

    shipping(cost) returns the cost it's given, and 50 if it's given none. Free shipping costs 0. Which call does it fail on?

  7. 7. Multiple choice

    Which of these changes is NOT refactoring?

  8. 8. Write the code

    total adds three prices written by hand, so it only works for three. Rewrite it with a loop so it works with any amount, even none. Change the body however you like; the name and the parameter stay the same.

  9. 9. Predict the output

    Someone moved the two lines into a function to avoid repeating them. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →