12 JavaScript Best Practices For Beginners

12 JavaScript Best Practices For Beginners
Mr. Unity Buddy's photo
Mr. Unity Buddy

Published on Jun 30, 2021

6 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Hello, buddies! Well, finally I started learning Javascript and found it is not so much hard at all. Also, I found some coding practices that would be great when shared!

1. Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

"If two operands are of the same type and value, then === produces true and !== produces false." - JavaScript: The Good Parts

However, when working with == and !=, you'll run into issues when working with different types. In these cases, they'll try to coerce the values, unsuccessfully.

2. Eval = Bad

For those unfamiliar, the eval function gives us access to JavaScript's compiler. Essentially, we can execute a string's result by passing it as a parameter of eval.

Not only will this decrease your script's performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!

3. Don't Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:

if(someVariableExists)
   x = false

Cosider this,

if(someVariableExists)
   x = false
   anotherFunctionCall();

One might think that the code above would be equivalent to:

if(someVariableExists) {
   x = false;
   anotherFunctionCall();
}

But the thing is, that buddy is wrong. In reality, it means:

if(someVariableExists) {
   x = false;
}
anotherFunctionCall();

As you'll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

4. Utilize JS Lint

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it'll quickly scan for any noticeable issues and errors in your code.

"JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems."

  • JSLint Documentation

5. Place Scripts at the Bottom of Your Page

Remember -- the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can't continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

If you have JS files whose only purpose is to add functionality -- for example, after a button is clicked -- go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

Better

<p>And now you know my favorite kinds of corn. </p>
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
</body>
</html>

6. Declare Variables Outside of the For Statement

When executing lengthy "for" statements, don't make the engine work any harder than it must. For example: Bad

for(var i = 0; i < someArray.length; i++) {
   var container = document.getElementById('container');
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the "container" element each time -- highly inefficient!

Good

var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

7. The Fastest Way to Build a String

Don't always reach for your handy-dandy "for" statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) - this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.

8. Reduce Globals

"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
var name = 'Jeff';
var lastName = 'Way';

function doSomething() {...}

console.log(name); // Jeff -- or window.name

Can be write better,

var DudeNameSpace = {
   name : 'Jeff',
   lastName : 'Way',
   doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeff

9. Comment Your Code

It might seem unnecessary at first(same with me), but trust me, you want to comment your code as possible. What happens when you return to the project months later, only to find that you can't easily remember what your line of thinking was.

Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code. So it would be better if you comment code like this,

// Cycle through array and echo out each name. 
for(var i = 0, len = array.length; i < len; i++) {
   console.log(array[i]);
}

But, don't comment on obvious code!

Comment only the code that someone can have doubts(like loops). Commenting obvious codeis a BAD practice. Commenting code like this make others angry.

var DudeNameSpace = {
   name : 'Jeff', //creating a variable 'name' and add 'Jeff' as the value
   lastName : 'Way',
   doSomething : function() {...}
}

10. Don't Use the "With" Statement

At first glance, "With" statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects. For example...

with (being.person.man.bodyparts) {
   arms = true;
   legs = true;
}

-- instead of --

being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;

Unfortunately, after some testing, it was found that they "behave very badly when setting new members." Instead, you should use var.

var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;

11. Use {} Instead of New Object()

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the "new" constructor, like so:

var o = new Object();
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function() {
   console.log(this.name);
}

However, this method receives the "bad practice" stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

Better

var o = {
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};

Note that if you simply want to create an empty object, {} will do the trick.

var o = {};

"Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc." - dyn-web.com

12. Use [] Instead of New Array()

The same applies to creating a new array.

Okay

var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';

Better

var a = ['Joe','Plumber'];

BONUS : Read, Read, Read.

Now I'm a huge fan of web development blogs, there really isn't a substitute for a book when grabbing some lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here are some of my JavaScript favorites on Hashode!

Add you favourite in the comments and happy coding!

 
Share this