Top 20 JavaScript Tips for Better Coding

JavaScript Tips: Boost your coding prowess with 20 proven tricks and techniques!

Meenakshi Agarwal
By
Meenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
21 Min Read
Super JavaScript Tips and Best Practices

Find out 20 JavaScript tips and best Practices. Whether a beginner or experienced, this coding guide will help you write clean, efficient, and robust JavaScript code.

Why Use JavaScript Tips and Best Practices

JavaScript is a must-have skill for any aspiring web developer. It’s a scripting language that powers dynamic and interactive web pages, making it one of the most popular client-side technologies.

if you want to stand out in the competitive field of web development, then you need to master JavaScript’s tips and best practices. So, get ready to learn these JavaScript tips and take your web development skills to the next level!

Note – The creator of JavaScript is Brendan Eich, also the co-founder of the Mozilla project.

20 JavaScript Tips and Coding Best Practices

Super JavaScript Tips and Best Practices
Super JavaScript Tips and Best Practices

How to Check JavaScript Version

It could make you curious to think about which version of JavaScript your browser is using. And, it is always good to know about the exact environment you are running the scripts.

So use the below HTML code. Copy-paste it into a file and save it as version_detect.HTML.

<html>
<body>
<head>
<script language="javascript">var js_version="1.0"</script>
<script language="javascript1.1">var js_version="1.1"</script>
<script language="javascript1.2">var js_version="1.2"</script>
<script language="javascript1.3">var js_version="1.3"</script>
<script language="javascript1.4">var js_version="1.4"</script>
<script language="javascript1.5">var js_version="1.5"</script>
<script language="javascript1.6">var js_version="1.6"</script>
<script language="javascript1.7">var js_version="1.7"</script>
</head>
<script language="javascript">
   document.write("JavaScript version = " + js_version); 
</script>

</body>
</html>

Once you open it in the browser, it should print the latest JavaScript version supported by your browser.

Avoid JavaScript Keywords as Variables

Like other languages, JavaScript also owns a set of keywords or reserved words. These terms have a specific purpose. You can’t use them as variables, labels, or function/method names.

Some of the known keywords are as follows:

var, if, else, for, while, instanceof, int, try, throw, goto, static, this, new

To get a full list, refer to this URL – [https://www.w3schools.com/js/js_reserved.asp].

Furthermore, check terms that get de-listed in the ECMAScript 5/6 editions. We are outlining a few here:

abstract, synchronized, float, final, transient, short

Despite their current status, you should not use them as variable names. It is because not all browsers are ECMAScript 5/6 compliant.

Don’t Mix Variables with Other Types

Since JavaScript is a weakly typed or untyped language, a variable can hold data of different types. It means that you can change a variable type even after initialization.

var status = "Success";
status = 1;

In the above JavaScript code, the status holds a string value initially. But in the next line, it switched to store an integer value. This snippet would run fine in any browser. However, this example doesn’t intend to suggest you follow the same approach. Instead, refrain from adopting such practices.

Use Inline Commenting Style

It is one of the JavaScript tips you may use quite frequently and increases your readability.

Comments make your code maintainable. The right commenting style is not only helps others but the author as well.

Usually, most scripting/programming languages allow adding inline comments and so does JavaScript. It helps to reduce the complexity of code by adding useful text. Keep it short and under a single line while using the inline style.

// Using inline comment style
var testvar = 1;
..

switch(addtoCart(order)) { // check order status
option 1:
option 2:
 ...
}

The code after the inline comment should always appear on a new line. Also, comment only at places that genuinely need an explanation like a self-containing logical unit.

Control Variable Scope

In JavaScript, a variable can either be in global or function-level scope. With the help of the [var] keyword, you can limit its scope.

So when you declare a variable, use [var] as a prefix. Place it either under the global or function scope. Not doing so would lead to incorrect behavior. You can observe from the below example.

Example-1

var iter = 0; // Nice - you explicitely created a global.
function iterations( ) {
   for (iter = 0; iter < 10; iter++) {
      document.write("iter : " + iter + " 
");
   }
}
iterations( );
document.write("iter : " + iter); // Global variable iter is now at 10.

Since the ‘iter’ variable inside the function doesn’t start with the [var] prefix, it won’t act like a function-level variable. On the contrary, it would reference the ‘iter’ variable from global space. So, it is always better to declare all variables using [var] irrespective of their scope.

Example-2

function iterations( ) {
   for (var iter = 0; iter < 10; iter++) {
      document.write("iter : " + iter + " 
");
   }
}

Use Eval Cautiously

It is one of the less-used but important JavaScript tips. In JavaScript, the eval() method allows the execution of any arbitrary code at run-time. However, it is always wiser to avoid using it. However, if it’s already present in your script, try to replace it with a better approach.

For example, the developers who often use [eval] may not know the Square Bracket Notation. Nor do they know about its side effects.

With [eval] in your code, the following issues may arise.

  • Unsafe use of eval could leave your code vulnerable to injection attacks.
  • The dynamic code would make debugging harder without any actual line number.
  • Runtime evaluation of instructions turns the execution visibly slow.

Avoid Using [with] in JavaScript

JavaScript provides a [with] statement which allows inserting an object at the front of the scope chain. It works for resolving a property or a variable reference against the object. The developers use it often as a shortcut to bypass deep references.

Problematic code

with (document.forms["Main"].elements) {
   input1.value = "test";
   input2.value = "test";
}

The problem with this code is that it doesn’t confirm if the input1 or input2 will get resolved as properties of the form array. It will first look for properties using given names. But if the check fails, the search will continue in the scope chain.

Once it reaches the global object, it begins treating [input1] and [input2] as global variables and bounds to set their [value]. However, all of this would lead to an error. So, the right approach is creating a reference to the reused object and using it to resolve references.

Correct version

var items = document.forms["Main"].elements;
items.input1.value = "test";
items.input2.value = "test";

Test conditions using === Instead of ==

JavaScript gives you two sets of equality operators:

Option#1 === | !==
Option#2 == | !=

The best practice is to prefer the first option for making the comparison.

The == (or !=) operator does an automatic type conversion if required. Whereas the === (or !==) operator won’t do any conversion. It simply matches the value and type. And it works faster than the ==.

If two operands belong to the same type and value, then === returns true, and !== produces false.

While using the operators == and !=, you may face issues when working with different types. In such cases, they’ll try to restrict the values without success.

Write Code with “Use Strict”

If you wish to get notified whenever you make a JavaScript violation while writing code, then you must use strict. It helps you maintain programming decorum by enforcing rules like declared variables, preventing the use of reserved words, and with the statement in your code.

The JavaScript ES6 modules already work in strict mode. If your current browser is not yet ES6 compliant, you may need to enable it yourself.

When you enable [use strict], it improves code quality and produces more readable code. And the script will become robust, less error-prone, and optimized.

The most efficient way to enable strict mode is by defining it as an anonymous function. By doing so, you can avoid its exposure to the global scope and say no to any unexpected eventualities.

// EnableStrict.js
"use strict"; // Things might go haywire

(function (){
    "use strict";
    // You are in control and write a great piece of code
})();

Careful! JavaScript is Case-Sensitive

Yes. Javascript is indeed case-sensitive. So, you’ll fall into a problem if your code uses variables in different cases but otherwise identical. Check the example:

Using variable names such as testVar and TestVar

That’s why no experienced developer will ever use the same names with just case variations. So, for better readability, most programmers follow the camelCase convention while naming variables.

Next, case sensitivity in JavaScript does not only affect variables but also reserved words/keywords, event handlers, and object properties or functions.

All keywords follow the lowercase style, e.g. [while, for, if, else], and so on. However, functions and object properties use the camelCase naming convention. The reserved word begins with a lowercase. And every successive first letter of each word should be in the capital case.

For example - toArray(), lastModified(), and so on.

So, always pursue good, uniform practices to name a custom identifier. It’ll help you prevent accidental clashes between different variables when you mean to create just one.

Typeof, InstanceOf, and Constructor

typeof is a JavaScript unary operator. It returns a string that describes the primitive type of a variable. While using typeof with null, it will return an [object]. Objects like [Array, Date] will also return [object].

The constructor is a property that all objects have. Alternatively, it entitles a unique class method. If an object or an array gets created without the constructor function, even then it will have a constructor property. However, I’ll refer to the fundamental object constructor type.

The instanceof is another JavaScript operator. It examines whether an object in its prototype chain has the prototype property of a constructor. If successful, it’ll return true or false otherwise.

var myArray = ["One", "Two", "Three"];
typeof myArray;   // return [object]
myArray  instanceof Array; // Will return true
myArray.constructor();  // Will return []

“SetInterval” or “SetTimeOut”

Don’t pass a string value as a parameter to SetInterval() or SetTimeOut() in your code.

setInterval(
"document.getElementById('myDiv').innerHTML += 'Current Status: ' + status", 5000
);

If you still do, then it’ll lead to Inefficient Code. Besides this, the code will run like the eval() function.

So, never try to pass a string to either of the SetInterval or SetTimeOut methods. Instead, use a function name.

setInterval(myFunction, 5000);

Cache [Array.Length] Inside a Loop

This tip may look simple at the onset. But it could hugely boost the performance when your code is iterating over a large array.

Let’s take an example where you are printing the content of an array.

for (var iter = 0; iter < tasks.length; iter++) {  
    console.log(tasks[iter]);
}

The above code will work just fine for smaller no. of tasks. However, the larger the size of the list, the more time it will take to recalculate its length. Calling it within the loop will impact performance.

You can prevent unnecessary delays by caching the following in a variable.

[tasks.length]

And then to use it inside the loop despite invoking the [tasks.length] method.

var iTaskLen = tasks.length;  
for (var iter = 0; iter < iTaskLen; iter++) {  
    console.log(tasks[iter]);
}

You can even use the Inline instructions and further reduce the code.

for (var iter = 0, iTaskLen = tasks.length; iter < iTaskLen; iter++) {  
    console.log(tasks[iter]);
}

Traverse the Array from the Rear

JavaScript arrays enable slicing to cut them into smaller sets. It is the function [Array.prototype.slice(begin, end)] which takes [begin] and [end] arguments and returns a slice. If you don’t pass the [end] argument, then the function will use the max value of the array.

Interestingly, this function does support -ve values as its parameters. And if we do so, it’ll return values from the rear. So, that’s the way we can efficiently traverse the array in reverse order.

var tasks = ['a', 'b', 'c', 'd', 'e', 'f'];
console.log(tasks.slice(-1)); // ['f']
console.log(tasks.slice(-2)); // ['e', 'f']
console.log(tasks.slice(-3)); // ['d', 'e', 'f']

Substitute Loop with Map()

JavaScript provides a map() method, similar to forEach() for iterating over an array. It accepts two parameters – a callback function, and a second parameter representing the [this], inside the callback function. However, the 2nd param is optional and barely used.

The primary difference between the two methods is that map() returns a new array whereas forEach() doesn’t return anything.

Look at the below example.

var items = [{
  id: 0,
  name: 'item 1'
},{
  id: 1,
  name: 'item 2'
}];

Here, we have a list of items which has two properties – [id] and [name]. If you wish to retrieve all identifiers, use the map() method.

var itemsIds = items.map(function(item) {
  return item.id;
});
console.log(itemsIds); // [0, 1]

You can get the above code more precise and powerful with the help of arrow functions.

var itemsIds = items.map(item => item.id);
console.log(itemsIds); // [0, 1]

Verify If Object has a Property

Here is a sample code that could help you avoid iterating through the object’s prototype.

for (var prop in testObj) {
    if (testObj.hasOwnProperty(prop)) {
        // do something with prop
    }
}

Store JavaScript Function as a Variable

Some situations may demand you to invoke a Javascript method at runtime.

Let’s assume – there is a foo() function you want to call at runtime. Below is a tiny JavaScript snippet that helps to invoke a method just by its name.

Call Function as String

var testFunc = "foo"; // Function Name to be called
var args = "This is a test parameter"; // Parameters list
 
// Set up the function
var func = window[foo];
 
// Invoke the function
func(args);

Replace All Occurrences of a String

This JavaScript tip can be quite useful for you in coding. The string class provides the replace() function for string substitution which supports RegEx. By default, it only substitutes the first occurrence. However, you can make it work for the entire string. Use a RegEx expression as shown in the below example.

var testStr = "Test - My first test";  
console.log(testStr = testStr.replace(/est/g, "ip")); // "Tip - My first tip"
console.log(testStr.replace(/ip/g, "rip")); // "Trip - My first trip"

Create Objects in JavaScript

In JavaScript, there are numerous ways to instantiate an object. Usually, most programmers call the new constructor to create objects.

Bad practice

var testObj = new Object();
firstName = 'ECMA';
lastName = 'Script';
someFunction = function() {
   console.log("Name is " + this.firstName + " " + this.lastName);
}

Modern JavaScript books don’t consider this approach as the best method.

Moving away from the C++ way of creating objects, JavaScript promotes using the [object literal] method, i.e., using {}.

Recommended

// Using object literal method {} replacing new.

var testObj = {
   testObj.firstName = 'ECMA';
   testObj.lastName = 'Script';
   testObj.someFunction = function() {
      console.log("Name is " + this.firstName + " " + this.lastName);
   }
};

// To create an empty object, use the curly braces i.e. {}.

var newObject = {};

Similarly, you can use square brackets [] (a.k.a. Array Literal) to declare an array. Alternatively, the Array class provides a constructor to create one. The difference is the constructor overwrites the content, but the [] doesn’t.

Usual approach

var myArr = new Array();
myArr[0] = 'United States';
myArr[1] = 'United Kingdom';

Recommended

var myArr = [United States', 'United Kingdom'];

No Try-Catch-Finally In a Loop

Finally, we will share the last JavaScript tip on error handling.

The JavaScript try-catch-finally clause functions as follows:

It creates a new variable every time the catch() block gets hit. This variable refers to the exception object.

So you can imagine how bad it is to use the try-catch-finally block inside a loop. It could result in creating unintended objects at runtime.

What should you not do?

var scripts = ['ES5', 'ES6'];  
for (var iter = 0, iLen = scripts.length; iter < iLen; iter++) {  
    try {  
        // Code that throws an exception 
    }  
    catch (ex) {   
        // Manage exception  
    } 
}

What should you be doing?

var scripts = ['ES5', 'ES6'];  
try { 
    for (var iter = 0, iLen = scripts.length; iter < iLen; iter++) {  
        // Code that throws an exception 
    } 
} 
catch (ex) {   
    // Manage exception  
}

Summary – JavaScript Tips & Tricks

Today, you read some of the best JavaScript tips and coding best practices. We hope you will find them useful and apply them in your code.

Also, we know you all are talented, so we invite you to share some of your cool JavaScript tips from your toolbox with us. Let’s all benefit from each other’s expertise and enrich our knowledge together. Here are some more useful resources, you should check out.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Enjoy coding,
TechBeamers.

Share This Article
Subscribe
Notify of
guest

0 Comments
Newest
Oldest
Inline Feedbacks
View all comments