7 Best Practices for JavaScript Development

7 Best Practices for JavaScript Development
COMMENTS (0)
Tweet

javascript

JavaScript is notorious for being the world’s most misunderstood programming language. At first glance, it seems easy and it certainly doesn’t take much time for an experienced developer to get the hang of it. However, it’s more powerful and complex than most people believe. While coding in JavaScript there are a few things you should keep in mind, which is what we’ll be talking about in this post.

1. Best Practice to follow when looping through an array in a FOR loop.

When looping through an array in a for-loop, it’s best to cache the length beforehand rather than calculating it on every iteration in the conditional statement. Since in a large application, and with large values and multiple loops, this can contribute to performance issues. This may not matter in many small instances but it’s certainly not good practice to calculate it on every iteration.

So instead of doing this:

for(var i = 0; i < myArray.length; i++){
// some task
}

You should do this:

var arrayLength = myArray.length
for(var i = 0; i < arrayLength; i++){
// some task
}

Alternatively, you can also do this:

for(var i = 0, arrayLength = myArray.length; i < arrayLength; i++){
// some task
}

2. Another point to keep in mind is that JavaScript does not create a separate scope for each code block.

So if you do this for example, what will happen?

{
var message = 'Hello, World!';
}

alert(message);

You may be thinking that the above code snippet will result in an error or an undefined value, when in fact this will just output “Hello, World!”. Even though your first guess would be correct for most programming languages but JavaScript doesn’t work that way. It doesn’t restrict the scope of the variable just to its block. However, ES6 does have block support with the ‘let’ keyword.

3. Do not apply styles on your elements.

Define a CSS class with those styles and add that class to the element instead. So instead of writing:

var myElement = document.querySelector(‘#something’);
myElement.style.color = ‘red’;

Do this instead:

var myElement = document.querySelector(#something’);
myElement.classList.add(‘red’);

4. Store Element to use same Selector

This mistake is quite common with developers who are used to using jQuery. It’s better to store that element in a variable rather than querying it every time you want to make a change to it.

Instead of writing the snippet below,

document.querySelector(‘#someButton’).classList.remove(‘disabled’);
document.querySelector(‘#someButton’).click();

It would be better to write the following:

var myButton = document.querySelector(‘#someButton’);
myButton.classList.remove(‘disabled’);
myButton.click();

5. Beware of ‘This’ Keyword

The this keyword in JavaSrcipt refers to the current context, which is often used incorrectly by developers.
Most common mistakes are made when using the ‘this’ keyword with setTimeout() or setInterval().

Let’s take a look at the following example.

var myObject = {
		name: 'Object A',
		toString: function(){
			return "This object's name is " + this.name;

		},
		delayedAlert: function(){
			setTimeout(function(){
				alert(this.toString());

			}, 500);
		
		}
};

 

In the above code snippet, if you call myObject.toString(), it will return “This object’s name is Object A”. Guess what’s going to be displayed when you call myObject.delayedAlert() ? Normally, this would trigger the toString method and display its result in an alert window, but it won’t in thise case.

That’s because in our setTimeout callback, this refers to the window object, and not our implementation of the toString method in myObject. So the output would be “[object Window]”

What you can do here is replace the setTimeout callback function definition with

alert(myObject.toString());

Now if you test the delayedAlert function, you’ll get the desired output. There is an even better way to do this though. And that is to store a reference of the current object (i.e. myObject) in the delayedAlert function, which can then be used by the setTimout callback (as shown in the code snippet below).

delayedAlert: function(){
	var self = this; // reference of current object
	setTimeout(function(){
		alert(self.toString());

	}, 500);

}

 

6. Make Changes after Document Loads

Another mistake that JavaScript developers often make is when they try to make changes whilst the document is still loading. At times like that, it’s best to keep in mind that there may be network issues that might cause the page to load gradually. So it’s better to make use of the ‘readystatechange’ and ‘DOMContentLoaded’ events in such scenarios.

7. Discard Unused Code

Lastly, do not keep unused code in your application. This is not a recommended practice.

Wrapping Up

By following these best practices you’ll not only make less mistakes while coding, you’ll also get better better command over JavaScript. Till next time!

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812