JavaScript Best Practices

Deborah Cohen

JavaScript is a quintessential component of almost any webpage, web-app, or web-based software. While it's features and capabilities can help developers create engaging, dynamic apps, there's also room for inefficiencies that can leave users with an inconsistent experience. We know it can be challenging to implement best practices when you're in the middle of a project with impending deadlines. However, there's never an excuse for messy code. Robert C. Martin (AKA Uncle Bob) put it best when he said:

"Even bad code can function. But if the code isn't clean, it can bring a development organization to its knees." — Robert C. Martin (Uncle Bob)

These best practices may seem like the starting point of JavaScript for beginners; however, no matter how seasoned a developer you may be, keeping them in mind helps you code more efficiently, develop your skillset, and makes it simple for other developers to build onto your project. If you're wondering how to learn JavaScript, starting with these best practices is a great place to start.

We cover the following JavaScript FAQs and best practices:

  • Variable and Function Naming Conventions
  • When/If To Use Global Variables
  • Keep Functions to Performing One Job at a Time
  • Utilize Progressive Enhancement
  • Use JSLint to Ensure Syntactical Quality
  • Placing Scripts at the Bottom of the Page
  • Commenting Best Practices
  • Software Alternatives to Commenting


Variable and Function Naming Conventions: Clear, Concise & Comprehensible

One of the first, and arguably most important best practices are to name variable and functions properly. Almost any developer can relate to jumping on a project and feeling the frustration ensue after coming across variable with short, undescriptive names like FQ1 or X9 or long, arguably too-descriptive names like UpdateNotificationHandlerIfFullMoon.RegisterMiddleWare. Don't get us wrong; there are a time and a place for short names and more descriptive names; just try not to go overboard on either.

Generally, you want to keep names as concise as possible without skimping on too many details. However, it can be hard to keep names brief when the category name and parents both have long names. But ultimately, the more concise, the clearer, and inevitably, the more comprehensible.

        "There are only two hard things in computer science: cache invalidation and naming things" – Phil Karlton

So, if you're like most developers, you may have reached a point where you're wondering how to write JavaScript variable and function names effectively. A good rule of thumb is that variable and function names should quickly tell you what it is and what's going on; no more, no less.  

There are many naming conventions you can consider. We recommend picking one and sticking with it. Consistency goes a long way, especially with variable names, which are case sensitive in JavaScript. If you're coding in JavaScript, follow camelCase for functions and variables. Using camelCase isn't usually debated as JavaScript itself, jQuery, and other JavaScript libraries all use it.

How to write JavaScript names using camelCase
Developers should write identifier names in JavaScript in camelCase. Coding example from https://www.robinwieruch.de/javascript-naming-conventions


JavaScript FAQs: Using Global Variables

Global variables best practices can seem a bit convoluted online. Some recommend omitting them altogether, while others recommend reducing your use of them when possible.

You may be wondering, 'Why do I need JavaScript globals?'. The answer? Technically, never.

Let's quickly delve into function scope in JavaScript for beginners. First, there are two types of scope: local scope and global scope (as we've already mentioned). Each function creates a new scope. This scope determines how visible, or accessible, these variables are. Although, variables defined inside a function aren't visible except when they're inside the function.

If a variable is declared outside a function, it's global. When this occurs, all functions and scripts on a webpage can access it. So, why the hate from many developers? Some argue this can be dangerous as scripts included after yours that contain the same variable or function names can overwrite your variables/functions.

"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries." Douglas Crockford

So, you may be wondering how to write JavaScript workarounds to reduce or eliminate globals. We've got you covered. Thankfully, doing so is pretty straightforward. Check out the code below:

How to write JavaScript with globals
Here, JavaScript is written with globals. Code example from https://code.tutsplus.com/tutorials/24-javascript-best-practices-for-beginners--net-5399


Compare it to this version below. The function is the same; however, by reducing the footprint of the 'DudeNameSpace" object, you've reduced the possibility of having other variables or functions overwrite it.

how to write JavaScript without globals
Reducing global footprints creates cleaner code in the long run. Code example from https://code.tutsplus.com/tutorials/24-javascript-best-practices-for-beginners--net-5399


Functions: One Job At a Time

In JavaScript, you should ensure that your functions only ever fulfill one job at a time.

Why?

If another developer joins you on your project, tries to build on it, or attempts to debug it or change it, they won't have to read through the entire code document to figure out what code performs which functions.

Keep in mind that this is incredibly relevant when creating common tasks or helper functions. Let's say while working on a project you realize you've been doing the same thing in a few different functions over and over again. To save time, you can create a more generic helper function, then reuse that functionality where it's needed.

Restricting your functions to only completing one job at a time also means you can change to an application or remove functionalities easier, quicker, and more accurately.


Utilize Progressive Enhancement

Many developers fall into the trap of assuming the majority of their viewers will have JavaScript enabled. The danger of this assumption is that every viewer won't. And if they don't, they may not be able to perform core functions on your site. This might be more common than you think.

Generally, you should design your site assuming viewers won't have JavaScript enabled. This way, they'll still be able to use your site for its core functions instead of being blocked because they can't or don't want to turn JavaScript on. It's easy to see how your site looks without JS with this Web Developer browser add-on for Firefox.

By designing for use without JavaScript, you'll begin to progressively enhance your layout, ensuring your site will work regardless of the technology available.


Use JSLint to Ensure Syntactical Quality

Clean and valid code should be the goal of any developer. It means more clarity, fewer bugs to fix, more straightforward handover to other developers, better security, and, ultimately, fewer headaches.

Some make the excuse that browsers are relatively lenient when it comes to JavaScript syntax. As far as best practices go, writing sloppy code that relies on a browser to make it work is never the right route. Sticking to a strict coding style will take your code from mediocre to excellent.

The best part? There is a nifty tool that makes it easier than ever: enter JSLint.

JSLint is the secret weapon to cleaner, bug-free code every JavaScript developer should have in their back pocket. If you're wondering how to design a website with JavaScript that's bug-free and clean in a reasonable amount of time, JSLint has you covered.

It provides a detailed report on any syntax warnings and what they mean. However, consider yourself warned. If there are any errors, JSLint WILL find them, and won't spare your feelings in doing so.

"JSLint will hurt your feelings. Side effects may include headache, irritability, dizziness, snarkiness, stomach pain, defensiveness, dry mouth, cleaner code, and a reduced error rate." – Douglas Crockford


Place Scripts at the Bottom of the Page

One of the primary questions coders just starting should be asking is 'how to design a website with JavaScript that loads quickly.' Creating pages that load quickly for the user is one of the most important goals every developer should have.

One way you can quickly achieve this is by placing scripts at the bottom of the page.

Why's this? 

When a browser is loading a script, it won't continue until the entire script has loaded. For example, if you've placed a script near the top, users will have to wait longer before noticing any progress. Do yourself, and future users a favor and make sure any JS files, especially those with the sole purpose of adding functionality, are placed at the bottom right before the closing body tag.


A Comment about Comments: Only When Needed

There's a lot of debate among developers on if or when to use JavaScript comments. For some background, comments are messages between developers or notes you leave yourself to explain your code. Some argue clean, excellent code should explain itself. If you're relying on comments, doesn't that mean your code may need more work and cleaning up?

On the other hand, explanations can be incredibly subjective. JavaScript alone has a plethora of naming conventions for variables and functions. There's much variability with coding, and it could be arguably presumptive to assume one developer will know how to write JavaScript with nuances identical to another.

When done right, comments never hurt anyone. By right, we mean ensuring your comments don't end up in the code that users see. If they do, you're not commenting right. As long as you steer clear of that, and use moderation, commenting can be an incredibly useful tool.


Software Alternatives to Commenting

Like we mentioned, when used right and in moderation, commenting has the potential to be a powerful tool. However, it's easy to overuse and could cause problems down the road.

In-line with best practices for JavaScript, you'll want to make sure you and your team have the best developer tools to ensure efficiency and quality for both coding and communication.

Instead of commenting, one of the best internal communication tools you and your team can use is CloudApp.

CloudApp can enable you to communicate visually with your team in mere seconds (let's be honest; coding involves enough typing as it is). Whether you need to annotate a screenshot, create a quick GIF, or make a quick screen recording to show precisely where that bug is, CloudApp can help.

You might be wondering, "is JavaScript free to use with CloudApp?". It is! You can download a free trial of CloudApp to see if it works well for you and your team (spoiler alert: you'll be hooked). It'll integrate seamlessly with your favorite tools like Slack, Jira, GitHub, and more.


Conclusion

JavaScript, like almost any coding language or developer tool, is continually evolving to keep up with progressions in frameworks and other technologies. By allowing developers to create engaging, dynamic sites have helped it become an integral part of most apps and websites. However, as with any coding dialect, there's room for inefficiencies and lousy code. Messy code can function, but it could also be the detriment of a development organization.

We know it can be hard to implement, but we hope this overview of JavaScript best practices helps you code more efficiently, improve your coding skillset and write code that is simple for other developers to build on. No matter if you're researching JavaScript for beginners, or if you're trying to improve your coding skills after a plethora of projects, keeping these JavaScript tips in mind from the beginning of a project can save you time and headaches down the road while helping users to have a more consistent experience on your webpage, mobile app or website.


Don't forget to pick up a free trial of CloudApp to try out with your team!

Join the Discussion

Gray X
Productivity Guide
Productivity is more important now than ever.

Learn how to improve your productivity with our guide.
Read Now