JavaScript 101-#20 – 7 tips for writing better JavaScript

Table of Contents

Have you ever though about ways to make your JavaScript more human-friendly and faster? To make it easier even for a beginner to read and learn from it? Well, there are many things you can do to achieve that or to at least move closer to this ideal. Today, we are going to discuss seven ways (I know how you like lists) you can make your scripts look less scary to the rest of the world who might not be that skilled as you are. Without further ado, let’s dive in …

#1 – Does it make sense?

Let’s start with variables. They are very useful because they allow us to store different types of data so we can use them later just by using the name of that particular variable. Here, we are getting to the first situation where bad practices can appear – naming of variables. We are not talking about naming rules in JavaScript, but rather about using names that are easy to understand. It is good to use your fantasy. However, curb yourself here a bit.

JavaScript:

// this is bad
var x = 27;
var fvx62 = 3.14159265358979;
function ifAgeIsHiherThanEighteen () {};

// this is better
var age = 27;
var piConstant = 3.14159265358979;
function legalAge() {};

#2 – Global & local variables

Next thing related to variables is scope in which they are created. In one of the previous posts of JavaScript 101 where we talked about functions, we also explored what scope is and that we can recognize two types. Global and local scope. If you are not familiar with scope, take a look at here first please. Don’t declare your variables in global scope. When possible, stick with local variables. This way, you will protect the code from being overwritten or to overwrite already existing code.

JavaScript:

// this is bad – global variables
var reps = 7, 
 sets = 6,
 timePerRep = 15;
function counter() {
 return reps*sets*timePerRep;
}

// this is better
function counter() {
 // local variables
 var reps = 7, 
 sets = 6,
 timePerRep = 15;
 return reps*sets*timePerRep;
}

When you need to store certain value and work with it inside some function, declare it in that function. This way, the variable will exist only when function will be called and it will be available only inside that function harmless to the code outside. You can also use JavaScript object to store all code you need (example below).

JavaScript:

// this is bad
var name = “John Doe”;
var title = “Senior Web Developer”;
var company = “TheoSoft”;
var skills = [“HTML”, “CSS”, “JavaScript”, “Ruby”, “PHP”, “Python”, “Java”];
function greeting() {
 alert(“Hi. My name is ”+name+” and I work as a ”+title+” in ”+company+”. My skills include ”+skills+”. Who are you?”);
}
greeting();

// this is better
var employee = {
 name: “John Doe”,
 title: “Senior Web Developer”,
 company: “TheoSoft”,
 skills: [“HTML”, “CSS”, “JavaScript”, “Ruby”, “PHP”, “Python”, “Java”],
 greeting: function() {
   alert(“Hi. My name is ”+this.name+” and I work as a ”+this.title+” in ”+this.company+”. My skills include ”+this.skills+”. Who are you?”);
 }
}
employee.greeting();

#3 – Have a coding style

Having a consistent coding style will help you and your colleagues understand your code and work faster. You will no longer find yourself in situation when you need some time to catch on some code you wrote couple years ago. With coding style this is no longer an issue. Any time you take a look at some of your earlier project, you will be able to say how does every part of it works and also how to optimize it.

#4 – Make it short

One great thing on CSS is the ability to use shorthands (padding, margin, font, etc.). You can easily do similar things in JavaScript too. Short notations can simplify and declutter your code in the same time. Let’s show how you can benefit from it on couple examples.

JavaScript:

// this is bad
var fruit = new Array();
fruit[0] = “Apple”;
fruit[1] = “Pear“;
fruit[2] = “Orange”;
fruit[3] = “Kiwi”;
if (num) {
 var x = num;
} else {
 var x = 21;
}
var answer;
if (age > 18) {
 alert(“You can drink here.”);
} else {
 alert(“Don't even think about it.”);
}

// this is better
var fruit = [“Apple”, “Pear“, “Orange”,“Kiwi”];
var x = num || 21;
var answer = (age > 18) ? alert(“You can drink here.”) : alert(“Don't even think about it.”);

#5 – Use modules

Even though we like generalists that can do everything any time, when it comes to JavaScript it is better to split your code into individual smaller functions focused on specific tasks. This way, you will also be able to extract the function you need and use it in another project without any need to modify it. This will be pretty useful while working on larger projects. So, divide your code into army of small functions and let them do their job.

#6 – Optimize the loops

Another place where you can optimize your code to make it faster and less performance demanding are loops. Quick way to achieve that is through small modification in initialization part. In this part you are declaring variables that will be used by the loop. For example, when you want to use for loop to loop through an array of elements. One way to do it is to declare one variable with starting index (probably 0) and compare it in condition part to length of the array.

JavaScript:

// this is bad
var languages = [“Esperanto”, “Slovianski”, “Unish”, “Spokil”, “Solresol”];
for (var i = 0; i < languages.length; i++) {
 console.log(languages[i]);
}

However, this slower and more performance-demanding than it has to be. Why? Because the loop will count the length of array EVERY time until the condition is met (i is equal to j). Smart fix is to create another variable (j) and store the length of array in it and then, in initialization part, modify the condition to compare i to j. This way, the loop will count the length only once, store it in variable j and then, on every iteration, it will just access this variable.

JavaScript:

// this is better
var languages = [“Esperanto”, “Slovianski”, “Unish”, “Spokil”, “Solresol”];
for (var i = 0, j = languages.length; i < j; i++) {
 console.log(languages[i]);
}

#7 – Keep CSS in stylesheet

While it might be tempting to use JavaScript to change the CSS of the elements, it can quickly turn into nightmare. If you need or want to change certain styles of some element(s), create new class in your stylesheet and then just append it to that element via JavaScript. Don’t set or modify the CSS directly in your script files. Keep these two separate.

JavaScript:

// this is bad
var button = document.getElementById(“button”);
button.onclick = function() {
 this.style.background = “#0281c6”;
 this.style.color = “#fff”;
};

// this is better
var button = document.getElementById(“button”);
button.onclick = function() {
 this.className += “js-clicked”;
}

Summary

There are countless ways to make your JavaScript code look and perform better and I hope that the few we discussed today will help you create fast and clean code.

If you liked this article, please subscribe so you don't miss any future post.

If you'd like to support me and this blog, you can become a patron, or you can buy me a coffee 🙂

By Alex Devero

I'm Founder/CEO of DEVERO Corporation. Entrepreneur, designer, developer. My mission and MTP is to accelerate the development of humankind through technology.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.