JavaScript Tips and Best Coding Practices for Beginners


JavaScript is one of the most popular client-side scripting languages. It is an essential skill for those who wish to make a career in professional web development. So, here, we are laying down some refreshing JavaScript tips and coding best practices that could help you ramp up quickly.

JavaScript is the de facto standard for implementing a seamless interaction between a user and the webpage. And almost, all modern-day browsers support it. It is the main technology behind driving the modern UX/server-side frameworks such as AngularJS and Node.JS. Hence, if you learn to write clean and robust JavaScript code, then it will increase your chances of getting hired.

Before we begin with the JavaScript tips, you should know the JavaScript is a scripting language which follows a set of specification known as ECMA script (ES). Its first edition came in 1997 and the last released version, the 7th edition is ECMA 2016. We’ve validated all of the below tips using Google Chrome browser following the ES 2016 standards. Please note that we may use different notation for ECMA scripts such as ECMAScript 2016 or ECMAScript 7 or ES 7.

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

Super-20 JavaScript Tips and Best Coding Practices

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

Determine JavaScript Version

It could make you curious to think 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 in a file and save as version_detect.HTML.

<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>
<script language="javascript">
   document.write("JavaScript version = " + js_version); 


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

Back to top

Avoid JavaScript keywords as variables

Like other languages, JavaScript also owns a set of keywords or reserved words. Since each of these has a specific purpose, so you can’t use them as variables, labels, or function/method names.

Some of the known ones are [var, if, else, for, while, instanceof, int, try, throw, goto, static, this, new].

However, you can find them all at this URL – [].

There are also few words which get de-listed in the ECMAScript 5/6 editions. Some of them are [abstract, synchronized, float, final, transient, short] and so on. But we still don’t recommend to use them as variable names because not all browsers are ECMAScript 5/6 compliant.

Back to top

Don’t invert Variable type after init

Since JavaScript is a weakly typed or untyped language, so it is possible for a variable to 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, you should refrain from adopting such practices.

Back to top

Usually, most scripting/programming languages allow adding inline comments and so does the JavaScript. It helps to reduce the complexity of code by adding a useful text. But you should 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:

Make sure the code always be on a new line after the inline comment. Also, don’t over-do it, use it at places which genuinely need an explanation like a self-containing logical unit.

Back to top

Control variable scope

In JavaScript, a variable can either be in global or function level scope. With the help of [var] keyword, you can limit its scope. So when you declare a variable, use [var] as prefix and then go ahead to place it either in global or function level scope. Not doing so would lead to incorrect behavior as you can see in the below example.


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 get prefixed with the [var], so 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.


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

Back to top

Don’t blindly use [eval]

JavaScript 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, then try to replace it with a better approach.

For example, the developers who often use [eval] are not aware of the Square Bracket Notation. Nor they know about its side-effects.

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

  • Unsafe use of eval could lead your code to be vulnerable to injection attacks.
  • The dynamic code would make it hard to debug without any actual line no.
  • Runtime evaluation of instructions turns the execution visibly slow.

Back to top

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 to act as a shortcut to bypass unusually 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 then 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 use it to resolve references.

Correct version

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

Back to top

Test conditions using === Instead of ==

JavaScript gives you two sets of equality operators: === | !== and == | !=. The best practice is to always prefer the former pair 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 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 any success.

Back to top

Make it a practice to 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, then you need to enable it yourself.

With [use strict], it is easier to improve code quality, produce more readable as well as test-friendly code. And the script will become robust, less error-prone and optimized.

The most efficient way to enable strict mode is by introducing it via an anonymous function. By doing so, you can avoid it from being exposed 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

Back to top

Careful! JavaScript is case-sensitive

Yes. It’s true that Javascript is case sensitive. So, you’ll fall into a problem if your code uses two different-cased, but otherwise identical, variable names such as testVar and TestVar. That’s why no experienced developer ever uses the same name literal with just case variations. So, for better readability, most programmers follow the camelCase convention while naming variables.

Next, the case sensitivity in JavaScript does not just affect variable names but also to 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 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 exampletoArray(), lastModified(), and so on.

So, always pursue good, uniform practices to name a custom identifier. It’ll help you avoid any accidental clashes of two different variables while you meant to create just one.

Back to top

Typeof, instanceof, and constructor

  • typeof is a JavaScript unary operator. It returns a string which describes the primitive type of a variable. While using typeof with null, it will return an [object]. And for objects like [Array, Date], it will also return [object].
  • The constructor is a property which all objects have. Alternatively, it entitles as 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 []

Back to top

“SetInterval” or “SetTimeOut”

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

"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 would.

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

setInterval(myFunction, 5000);

Back to top

Cache [array.length] inside a loop

This tip may look simple at the onset. But it could hugely boost the performance when you have a code traversing a big array in a loop.

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

for (var iter = 0; iter < tasks.length; iter++) {  

The above code will work just fine for smaller no. of tasks. However, more is the size of the list, more time it will take to recalculate the length. And calling it in the loop will impact performance.

You can prevent unnecessary delays by caching the value of [tasks.length] in a variable. And then to use it inside the loop in spite of invoking the [tasks.length] method.

var iTaskLen = tasks.length;  
for (var iter = 0; iter < iTaskLen; iter++) {  

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

for (var iter = 0, iTaskLen = tasks.length; iter < iTaskLen; iter++) {  

Back to top

Traverse an array from the rear end

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, then it’ll return values from the rear. So, that’s the way we can efficiently traverse the array in the 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']

Back to top

Substitute Loop with map()

JavaScript provides 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. Although, 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, then use the map() method.

var itemsIds = {
console.log(itemsIds); // [0, 1]

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

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

Back to top

Verify if an object has a property

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

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

Back to top

JavaScript function using a string

In some cases, you may have to invoke a Javascript method at runtime.

Let’s assume – there is a foo() which 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

Back to top

Replace all occurrences of a string

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 by using 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"

Back to top

Create objects in JavaScript

In JavaScript, there are no. of 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);

But modern JavaScript books don’t consider this approach as one of the best methods.

Moving away from the C++ like ways for creating objects, JavaScript promotes to use the [object literal]method, i.e., using {}.


// 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';


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

Back to top

No try-catch-finally inside a loop

The try-catch-finally clause functions in such a way that it creates a new variable each time the catch() block gets hit. This variable refers to the exception object.

So you can imagine how bad is to use the try-catch-finally block inside a loop. It could result in creating the 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  

Back to top

Summary – JavaScript Tips & Best Practices

We attempted to bring you a canny set of top JavaScript tips and coding best practices. Hoping that you would love them all, use a few we are ending this post.

However, you too can showcase your skills here by sharing a few of cool JavaScript tips from your toolbox. So, all of us, the geeks would benefit reading them and enrich our knowledge.

If you liked the post, then please don’t miss to share it with friends and on social media (facebook/twitter).


Source link


Leave A Reply