May 20, 2020

JavaScript Best Practices in Lightning Components

No items found.
EMPAUA Salesforce Solutions

JavaScript is the coffee-based (not really) programming language that forms one of the three fundamental magics underpinning all of the websites we use on a daily basis and is responsible for the web revolution that has made things like Salesforce such an integral part of how we do business and lead our lives.So JavaScript is an important part of the web, but what about Salesforce? What about our favourite platform, Salesforce, where can it be found? You may have heard about the client-side controller found in Lightning components (both Aura and LWC) and you’d be correct! The primary place we write JavaScript on the Salesforce platform these days is within custom components, but it doesn’t stop there.Visualforce probably is a place you’d think of, you’ve probably heard or written Apex controllers for those, so they don’t use JavaScript, right? Not so fast! Visualforce’s main technology is definitely the Apex controller, but JavaScript can be used to augment the user experience into something much more modern and enjoyable. Think about your favourite AppExchange package, any Visualforce pages there are probably utilising JavaScript to give you the experience that gives it its place on your must install list.

Variable Naming

Despite seeming like one of the simpler aspects of programming, proper variable naming can have some of the greatest impacts when producing code that won't induce hair ripping emotions in several months' time.

To keep your hair intact:

  1. Camel Case – This is where the capitalisation of the words look like a camel’s humps, for example, myFancyVariable. We always want to keep the first letter as a lowercase, not only does this help readability but in Lightning Web Components failure to do so can cause us issues when referring to them in HTML!
  2. Be descriptive – think about what the purpose of this variable is and the data it holds, this should be your first port of call when choosing a name.
  3. Keep it simple! - If you’ve followed the previous point, you might be tempted to make a super long variable name such as contactsBelongingToAccountArray. We can immediately tell what the purpose of this variable is, but we could write this in a simpler way, such as account contacts. Not only is no information lost here, but it’s also far easier for us developers to quickly read and quickly type.
  4. Maximum of 3 capitals in a row – This one is purely from a readability point of view. Having more than 3 capitals in a row, especially for abbreviations, can make it really difficult to quickly glance at a piece of code and read its name. For example, HTTPRequest is more difficult to take in than HttpRequest.

While these bullets may seem simple, mastering them is a very difficult skill. Don’t be afraid to ask a friend or colleague to double-check your names after you’ve written them, it’s a great way to practice!

Function Naming

You might be thinking, “right now I understand variable naming so I should just apply the same to functions, right? Functions are just variables that do something after all” and you’d be right!For functions, we want to follow the same basis as variable naming, but with an additional aspect thrown in. Our function names should start with an action eg submitForm. This makes it much easier at a glance to identify a function and draws a mental separation between functions and variables, especially when you’re passing functions around as variables in callbacks!


Now that we’ve mastered variables and function naming, we move on to one of the more exciting parts of JavaScript and component design, events!In case you think events are just things you drink at, in JavaScript land they are signals we use to alert other pieces of code that something has happened and that it should respond to it. These signals play a key role in reacting to user interaction (eg clicking a button), or for other code to react to something that has occurred when building standalone components.Aura and Lightning Web Components (and by extension Visualforce and the wider web) run on two different methodologies for sending and receiving events. These are traditional events (component events in Aura) and Publisher Subscriber events (Application events in Aura). While the end result is the same, they have fundamental differences in how they're made and how they should be treated.Traditional Events (Component): These events are used to communicate in a Child -> Parent manner and are highly predictable in nature. They should be named entirely in lowercase (eg on right-click). You attach them to components and can prevent their propagation if somethings not quite right (eg stop submitting an invalid form)Publisher Subscriber events: Used when we want to communicate with sibling components - avoid using these where there is a child -> parent relationship. Requires custom code to handle the communication and firing of event responses - take a look at this trailhead for a great starting module). Handlers must unsubscribe when done - failure to do so can lead to unforeseen consequences when a component reacts to an event after it is no longer required to do so.

EMPAUA Salesforce Solutions

Example of a traditional event in a Lightning web component - This event could be handled with an on clicked event handler.

Code Comments

Comments in code are a hotly debated topic, with people saying you should add as many as possible and others saying they should be avoided entirely. In reality, the best practice is somewhere in between.

  • Whenever you are writing a block of code you should ask yourself three questions: Are my variables and functions well named? Is there some outside context required? If I was drunk, could I understand this?

If you answer no to any of the above three questions, a comment may be a good idea! Now then, that comment should just reiterate what's going on in the code, that’s a bit pointless since we could just read that, instead, it should be a simple description of the why behind the code, not the what. To put it another way, a good comment describes why something is the way it is and isn't just a description of what is there.It’s super important to remember that we don't write code for the computer to understand, we write it for our fellow humans, so keeping everything nice and clear without any ambiguity is key to writing good code.

Curly Braces

Curly braces have a love-hate relationship with programmers, some love their verbosity and explicitness and others hate them for being too verbose!In programming languages such as JavaScript, we always want to include them for any if statements or loops. Failure to do so is a surefire way to introduce a ticking time bomb into your codebase that will be a real pain to debug when it rears its head. For a good explanation and examination of this, pop a quick search in for “Apple goto fail” which was a security bug caused by skipping some curly braces.

EMPAUA Salesforce Solutions

Debug Statements

Sticking debug statements into our code is a really useful development and debugging tool for us developers while we are producing solutions. Sometimes it's really useful to print something about our code to review at our leisure.While there is nothing wrong and is actually encouraged, with included debug statements while we develop, these should be removed from any code that goes into a production environment (NodeJs is an exemption to this!). Sticking details about the inner workings of our code in an easily accessible format opens up the opportunity for somebody with nefarious intentions to get a good glimpse into how our components work, and how to exploit them.For example in Google Chrome, it’s trivial to modify the code of Aura components on a page and our debug statements may provide inspiration for an attack vector. Let’s keep things safe and use the browser’s debugging tools and breakpoints when in production (or use a custom logged if you’re feeling fancy!).Another nugget of advice when using debug statements is to only log primitive values - so Strings and Integers, rather than objects as a whole. Without getting into the technicalities behind this, logging objects to the console creates a reference to the object that was logged.This means that the garbage collector (the thingy that clears up memory) will see a reference to the object and keep it around, wasting potentially valuable RAM! As Well as that, in Aura components, it can prevent the component from being destroyed, keeping all of its event handlers active, those Application events powering your component can easily create a headache when they fire for no apparent reason due to a ghost component haunting you!Hopefully, you feel empowered (pun intended) to write cool, clean JavaScript code going forward that saves you time in the future. Next time you review some code and think “This is pretty good!” and realise it’s your own, give yourself a pat on the back and share the knowledge you’ve learnt.

EMPAUA Salesforce Solutions

By Alexander Crisp, Salesforce Developer - connect with him!

EMPAUA Salesforce Solutions

Salesforce Partner EMPAUA

Do you need Salesforce support?

Book a demo and let our team implement smart solutions for your business.

Want to join the team?

Take a look at our job openings and be part of our mission.

Related posts

Ready to start your digital transformation?