Design comparison
Solution retrospective
Hello, so I finally finished this project, which should be completely bug-free. Anything appearing or not appearing should be part of my intended logic. But I have one problem. I have no idea how to create clean, reusable, and maintainable javascript code. It's just a big chunk of complicated, unclean, and bad-looking code. Any ideas on how to improve that and learn how to create clean, reusable, and maintainable code?
Community feedback
- @fadhilradhPosted over 2 years ago
Hi Daniel,
First off I’d say that your result is great! It looks exactly like the design and works well. Well done!
I have taken look at your source code and I have a suggestion for your question about how to refactor your main.js file.
First, I see a lot of code inside your
updateBill
function and it’s not very readable. What you can do is you can extract every code inside an if or else if to another function. Example : Instead of :if(foo) { …foocode.. } else if (bar) …barcode… {
You can write as :
if (foo) { doFoo() } else if (bar) { doBar() }
This is more readable for the one who will read your code (your co-workers) and cleaner as it follow the principle of one function should only do one thing. Also, make sure your function name is meaningful and should be a verb.
Secondly, you can further improve your code by separating your code into several files, grouping similar functions and variables inside a file and making use of
import
andexport
statements.For example you can split into three files : main.js for storing your global variables, updateBill.js for updating functions and utils.js for other functions. Then, you can export function to be available in another file. For example :
// updateBill.js export function updateBill() { …doAwesomeThings() }
// main.js import { updateBill } from “./updateBill.js” updateBill()
You can do this for every other function and group similar functions in one js file.
Hope it helps and good luck Daniel !
Marked as helpful2@DanoSvKPosted over 2 years ago@fadhilradh These are great advices. Thanks. I will definitely try to refactor this code.
1@fadhilradhPosted over 2 years ago@DanoSvK Hi Daniel, sorry I forgot to mention, you need to make change to your HTML file : Add
type="module"
to your link to main.js file. This will make your JS files able to import and export function and variables to each other. Otherwise there will be an error.1@DanoSvKPosted over 2 years ago@fadhilradh Thanks man, I appreciate your time and effort 👍
1
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord