To make this simple, let’s look at a really contrived example. For all click events that occur within the
<div id="app"></div> element, we want to log the clicked element to the console.
Immediately-invoked function expression
For most projects, I want my code to run immediately when the page loads. I also want to keep it out of the global scope to avoid naming conflicts with other scripts. To do this, I start with an immediately-invoked function expression (IIFE, pronounced ‘iffy’):
At the top of my IIFE, I add all my global variables. It’s nice to have them all in one place at the top so you can easily find and change them.
For this example, we just need to get the
Next, I add all my functions. Using named, modular functions really helps keep your code more readable and maintainble.
For this example, we’ll create a
logElement() function that logs the clicked element to the console.
Inits & Event Listeners
Finally, I add my inits and event listeners to the bottom of the IIFE. This is where I put any code that actually initializes the app, as opposed to just creating variables and functions.
For this example, we need only add our click handler to the
I’d like to thank Chris Ferdinandi and Todd Motto for influencing my approach. You can find more boilerplates on The Vanilla JS Toolkit, which Chris maintains. Let me know if you’d like me to write about them 😊
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!