Refactoring
JavaScript · Unit 19: Clean code
- Full plan
- JavaScript
- 9 exercises
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. Predict the output
What does this code print?
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. Complete the code
Fill in the blank to also charge the 400 pair of pants with its tax.
4. Put the lines in order
Put
allWithTax(prices)in order: a new array with each price plus its 10%.5. Complete the code
Fill in
passed, which returnstrueif the score reaches 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. Multiple choice
Which of these changes is NOT refactoring?
8. Write the code
totaladds 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. Predict the output
Someone moved the two lines into a function to avoid repeating them. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.