How to Write Your Own JavaScript Code (Method / Pattern / Rules)

How do your write your custom JavaScript code? Are there any rules or pattern to follow? Let say you are writing simple vanilla JavaScript code or you are working with jQuery. Which method, pattern you shall use? Of course complex JavaScript libraries and frameworks have their own set of rules. But for vanilla JavaScript or jQuery and in case of writing your custom JavaScript file it’s kind of seems like freedom. You can begin and end anywhere and type any piece of code or function in any way, method or anywhere. But is it really?

But its good to set rules and have a pattern. A pattern will help you write clean code. It will help you understand and manage your code later on. And other web developers in team will also be able to understand, use that code and will appreciate it. Will you throw all the code in JavaScript file randomly? Some of it will not even work because that will need firing after DOM is loaded? Are you including checks for DOM loaded, window loaded and window resized?

If you use document ready (DOM loaded) and window resized checks. Will you duplicate your code in both these check if you need the code in both events? So there are DOM loaded, Window Resize, Window Scroll and Window loaded checks. These are kind of our check points, that we can use to our advantage and use code inside these depending on when we want our particular code to be executed.

So this is what we will do. We will use functions to write our code. Each piece of code or functionality will be in a single function. So that we can use that function in any of those pointers on need. we have DOM Loaded and Window loaded events available in vanilla JavaScript. Add event listeners for DOMContentLoaded and window load and use functions to call code when these events are being triggered.

I use event listeners at the top and then I keep my functionalities in separate functions and then i call my functions inside those event listeners depending on need. I need screen check on DOM ready and on Window resized to check window width. So I am using that function in two locations but it is not duplication. I am just calling my function twice in both scenarios.

English Version

Urdu/Hindi Version

So how do you write your custom JavaScript file? What method do you use? Which rules do you follow? I want to know. Let me know in comments.