How can I make this code cleaner ?

Hello, How do I make this code cleaner ? I have main js file and this dom manipulation js file which I export to main js file. Should I declare dom variables inside functions they are used in instead of putting them on top of file? Is it correct to have init() function, like in my code, which holds other functions and then export it to main js file and call it there? All recommendations are welcome, thanks !
No description
No description
1 Reply
13eck
13eck12mo ago
If you want people to read your code (especially if you're asking for critique) don't use screen shots. We can't read them very well nor can we copy/paste the code to make edits. Not to mention the complete lack of accessibility of a picture. Either copy/paste the code directly here in the question (be sure to read #How To Ask Good Questions to learn how to format code blocks) or use something like a Github Gist or Codepen. However you do it, we need text please. I can, however, answer a few of your questions:
Should I declare dom variables inside functions they are used in instead of putting them on top of file?
They should be declared in the function they're used, unless they're used in multiple function that run multiple times. Otherwise your variables are taking up memory for no reason (of course memory is pretty cheap these days, so that's more a personal preference).
Is it correct to have init() function, like in my code, which holds other functions and then export it to main js file and call it there?
"Correct"? Maybe. Considering it's only ever run once it seems a decent way to do it. Without knowing what the rest of your code does we can't say for sure, though. Looking at a lot of your code, however, it seems like you would get a lot of milage out of learning event delegation. You can read up on Go Make Things, Javascript.info, Free Code Camp, or hit up your favourite web search engine. But basically it's the idea that you don't put an event listener on every element that could have an event, but instead put it on a common parent element and have one event listener. That listener delegates action based on what element was acted upon.
Want results from more Discord servers?
Add your server