Top 10 Mistakes that Javascript Developers Make

Top 10 Mistakes that Javascript Developers Make

Indeed, even the best JavaScript Programmers make mistakes. Sometimes, these mistakes cause your program to not produce the results that you needed, and sometimes they cause the program to not run at all. Here are 10 Javascript Mistakes that developers at all levels frequently make. But If you keep these 10 Mistakes in your mind, coding and debugging will be less of a headache.

 1. Missing Curly Braces

JavaScript beginners are often tend to miss curly braces after statements like if,  while and for. Although it is allowed, you should be extra careful, because this practice can frequently hide issues and be the wellspring of bugs. These are the Most common Javascript Mistakes made by developers.See the below example:

hello('Madhu Kanumuri');
function hello(name){
            if(name === undefined)
                   console.log('Please enter a username!');
                   fail();

            success(name);
}

function success(name){
            console.log('Hello, ' + name + '!');
}

function fail(){
            throw new Error("Name is missing. Can't say hello!");
}

Although the fail() call is indented and appears as if it belongs to the if statement, it doesn’t. It is always called. Therefore, it is a good practice to surround blocks of code with Curly Braces, although there’s just one statement concerned.

2. Misplacing and Missing Semicolon

Because of a misplaced semicolon , this code block will execute regardless of the value of x :

<p id="misplaced_semicolon"></p>

<script>
var x = "Madhu";
if (x == "Kanumuri");
{
document.getElementById("misplaced_semicolon").innerHTML = "Hello Kanumuri";
}
</script>

At the point when JavaScript is parsed, there is a procedure known as automatic semicolon inclusion. The purpose of this feature is to make JavaScript more approachable and easier to write by beginners.

In the Below example, there is a semicolon missing on line 1, the parser assumes that the opening bracket( ” [  “) on line 3 is an attempt to access a property using the array accessor syntax, and not a separate array, which is not what was intended and results in a type error. So always write semicolon to fix these errors.

console.log('Welcome to Fix The Error!')

['John', 'Cook', 'Smith', 'Warne'].forEach(function(name){
            hello(name)

})

function hello(name){
            console.log('Hello, ' + name + '!')
}

 

3. Misunderstanding Javascript Scopes

A difficult concept for beginners to understand is JavaScript’s scoping rules and closures. Here is an example:

for(var i = 0; i < 15; i++) {
            setTimeout ( function() {
                        console.log(i+1);
            }, 100*i);
}

Functions retain visibility to variables in their parent scopes. But since we are postponing the execution with a setTimeout, once the time comes for the functions to actually run, the loop has already finished and also the ‘ i ‘ variable is incremented to 11.

To fix the bug, wrap the code in a self-executing function expression:

for(var i = 0; i < 15; i++) {
            ( function(i) {
                        setTimeout( function() {
                                    console.log(i+1);
                        }, 100*i);
            } ) (i);
}

Above function works, because it copies the i variable by value and keeps a private copy for each timeout function.

4. Assigning Null to Reference Types to Avoid Javascript Mistakes

It’s also one of the Most Common Javascript Mistakes that the developers don’t assign null value to Variables of reference types  (object or Array)  when there utilize is done. See the below example:

var arr = [10, 20, 40];

//perform some processing on arr

//assign null to arr when its use is finished

arr = null;

The advantage of assigning null to reference types is that the garbage collector of js engine automatically reclaims the memory utilized by that variable. Keep in mind that this is often specially important for variables whose scope is massive like global variables. Local variables are automatically destructed when they are out of scope.

5. Forget that == is n’t the same as ===

==   Which compares value

=== Which compares object references

See the below example:

var x = ReturnsAnObject()
var y = ReturnsAnObject()
if (x == y)
   console.log("same", x, y)
else
   console.log("different", x, y)

Above example will likely show “same [object] [object]”

var x = ReturnsAnObject()
var y = ReturnsAnObject()
if (x ===y)
   console.log("same", x, y)
else
   console.log("different", x, y)

Above example always show “different [object] [object]” if x and y are not the same objects

Important : when comparing something to null, it’s considered more appropriate to use === or !==.

6. Incorrect references to “this” Keyword :

See the below example:

Game.prototype.restart =  function () {
  this.clearLocalStorage() ;
  this.timer = setTimeout(function() {
  this.clearBoard();    // what is 'this' ?
  }, 0);
};

Executing the above code results in the following error

Uncaught TypeError: undefined is not a function

The reason you get the above error is because, once you invoke setTimeout(), you’re actually invoking window.setTimeout(). As a result, the anonymous function being passed to setTimeout() is being defined within the context of the window object, that has no clearBoard() method.

 

Alternatively, in newer browsers, you’ll use the bind() methodology to pass within the correct reference:

Game.prototype.restart = function () {
  this.clearLocalStorage();
  this.timer = setTimeout(this.reset.bind(this), 0);  // bind to 'this'
};

Game.prototype.reset = function() {
    this.clearBoard();   
};

 7. Accessing Arrays with Named Indexes

Many programming languages support arrays with named indexes. Arrays with named indexes are known as associative arrays. JavaScript doesn’t support arrays with named indexes.

In JavaScript, arrays use numbered indexes. Here is the example:

var student = [];
person[0] = "Amir";
person[1] = "Khan";
person[2] = 48;

var x = person[0];           // person[0] will return "Amir"
var y = person.length;      // person.length will return 3

 

In JavaScript, objects use named indexes. Here is the example:

var person = [];
person["firstName"] = "Amir";
person["lastName"] = "Khan";
person["age"] = 48;

var x = person[0];           // person[0] will return undefined
var y = person.length;      // person.length will return 0

 

 8. Misunderstanding Javascript String Replace() Method

A common mistake is assuming the behaviour of the string replace method will impact all possible matches. In actuality, the javascript string replace method only changes the first occurrence. To replace all occurrences, you need to set the global modifier.

Example :

var String = "Hello! Thank You";
  myString = myString.replace(/ /,"%20");      // "Hello!%20Thank You"
  myString = myString.replace(/ /g,"%20");   // "Hello!%20Thank%20You" 

9. ParseInt should include two arguments

 The most common error with parsing integers in javascript is that the assumption that parseInt returns the integer to base 10. Don’t forget the second argument, the radix or base, which might be something from 2 to 36. To make sure you don’t screw up, always include the second parameter.

 10. Ineffective DOM Manipulation

Adding a DOM element is an expensive operation. Code that adds multiple DOM elements consecutively is inefficient and sure not to work well.

One effective alternative when multiple DOM elements should be added is to utilize document fragments instead, subsequently enhancing both efficiency and performance.

For Example :

var list = document.getElementsByTagName("list");
var fragment = document.createDocumentFragment();
for (var el = 0; el < elems.length; el++) { 
    fragment.appendChild(elems[el]);
}
div.appendChild(fragment.cloneNode(true));

Submit your Javascript Errors, issues or problems and get it fixed by an expert Javascript Programmer