Saturday, November 21, 2026
HomeSoftware EngineeringThe ten Most Frequent JavaScript Points Builders Face

The ten Most Frequent JavaScript Points Builders Face

[ad_1]

Editor’s be aware: This text was up to date by our editorial workforce on July 19, 2022. It has been modified to incorporate latest sources and to align with our present editorial requirements.

Right now, JavaScript is on the core of just about all fashionable internet purposes. That’s why JavaScript points, and discovering the errors that trigger them, are on the forefront for internet builders.

Highly effective JavaScript-based libraries and frameworks for single web page utility (SPA) growth, graphics and animation, and server-side JavaScript platforms are nothing new. JavaScript has actually develop into ubiquitous on the earth of internet app growth and is subsequently an more and more essential ability to grasp.

At first, JavaScript could appear fairly easy. And certainly, to construct primary JavaScript performance into an online web page is a reasonably easy process for any skilled software program developer, even when they’re new to JavaScript. But the language is considerably extra nuanced, highly effective, and sophisticated than one would initially be led to consider. Certainly, lots of JavaScript’s subtleties result in a variety of frequent issues that preserve it from working—10 of which we talk about right here—which are essential to pay attention to and keep away from in a single’s quest to develop into a grasp JavaScript developer.

JavaScript Situation #1: Incorrect References to this

There’s no scarcity of confusion amongst JavaScript builders concerning JavaScript’s this key phrase.

As JavaScript coding strategies and design patterns have develop into more and more subtle through the years, there’s been a corresponding improve within the proliferation of self-referencing scopes inside callbacks and closures, that are a reasonably frequent supply of “this/that confusion” inflicting JavaScript points.

Take into account this instance code snippet:

Sport.prototype.restart = perform () {
    this.clearLocalStorage();
    this.timer = setTimeout(perform() {
    this.clearBoard();    // What's "this"?
    }, 0);
};

Executing the above code leads to the next error:

Uncaught TypeError: undefined will not be a perform

Why? It’s all about context. The explanation you get the above error is as a result of, if you invoke setTimeout(), you’re truly invoking window.setTimeout(). Consequently, the nameless perform being handed to setTimeout() is being outlined within the context of the window object, which has no clearBoard() methodology.

A conventional, old-browser-compliant answer is to easily save your reference to this in a variable that may then be inherited by the closure; e.g.:

Sport.prototype.restart = perform () {
    this.clearLocalStorage();
    var self = this;   // Save reference to 'this', whereas it is nonetheless this!
    this.timer = setTimeout(perform(){
    self.clearBoard();    // Oh OK, I do know who 'self' is!
    }, 0);
};

Alternatively, in newer browsers, you should utilize the bind() methodology to move within the correct reference:

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

Sport.prototype.reset = perform(){
    this.clearBoard();    // Ahhh, again within the context of the appropriate 'this'!
};

JavaScript Situation #2: Pondering There Is Block-level Scope

As mentioned in our JavaScript Hiring Information, a typical supply of confusion amongst JavaScript builders (and subsequently a typical supply of bugs) is assuming that JavaScript creates a brand new scope for every code block. Though that is true in lots of different languages, it’s not true in JavaScript. Take into account, for instance, the next code:

for (var i = 0; i < 10; i++) {
    /* ... */
}
console.log(i);  // What is going to this output?

Should you guess that the console.log() name would both output undefined or throw an error, you guessed incorrectly. Imagine it or not, it’s going to output 10. Why?

In most different languages, the code above would result in an error as a result of the “life” (i.e., scope) of the variable i can be restricted to the for block. In JavaScript, although, this isn’t the case and the variable i stays in scope even after the for loop has accomplished, retaining its final worth after exiting the loop. (This conduct is thought, by the way, as variable hoisting.)

Assist for block-level scopes in JavaScript is out there by way of the let key phrase. The let key phrase has been extensively supported by browsers and back-end JavaScript engines like Node.js for years now..

If that’s information to you, it’s price taking the time to learn up on scopes, prototypes, and extra.

JavaScript Situation #3: Creating Reminiscence Leaks

Reminiscence leaks are nearly inevitable JavaScript points in the event you’re not consciously coding to keep away from them. There are quite a few methods for them to happen, so we’ll simply spotlight a few their extra frequent occurrences.

Reminiscence Leak Instance 1: Dangling References to Defunct Objects

Take into account the next code:

var theThing = null;
var replaceThing = perform () {
  var priorThing = theThing;  // Maintain on to the prior factor
  var unused = perform () {
    // 'unused' is the one place the place 'priorThing' is referenced,
    // however 'unused' by no means will get invoked
    if (priorThing) {
      console.log("hello");
    }
  };
  theThing = {
    longStr: new Array(1000000).be part of('*'),  // Create a 1MB object
    someMethod: perform () {
      console.log(someMessage);
    }
  };
};
setInterval(replaceThing, 1000);    // Invoke `replaceThing' as soon as each second

Should you run the above code and monitor reminiscence utilization, you’ll discover that you just’ve obtained a big reminiscence leak, leaking a full megabyte per second! And even a handbook Rubbish Collector (GC) doesn’t assist. So it seems like we’re leaking longStr each time replaceThing is named. However why?

Reminiscence leaks are nearly inevitable JavaScript points in the event you’re not consciously coding to keep away from them.

Let’s look at issues in additional element:

Every theThing object accommodates its personal 1MB longStr object. Each second, once we name replaceThing, it holds on to a reference to the prior theThing object in priorThing. However we nonetheless wouldn’t suppose this could be an issue, since every time by, the beforehand referenced priorThing can be dereferenced (when priorThing is reset by way of priorThing = theThing;). And furthermore, is barely referenced in the primary physique of replaceThing and within the perform unused which is, in reality, by no means used.

So once more we’re left questioning why there’s a reminiscence leak right here.

To know what’s occurring, we have to higher perceive the interior workings of JavaScript. The standard method that closures are carried out is that each perform object has a hyperlink to a dictionary-style object representing its lexical scope. If each features outlined inside replaceThing truly used priorThing, it could be essential that they each get the identical object, even when priorThing will get assigned to time and again, so each features share the identical lexical atmosphere. However as quickly as a variable is utilized by any closure, it leads to the lexical atmosphere shared by all closures in that scope. And that little nuance is what results in this gnarly reminiscence leak.

Reminiscence Leak Instance 2: Round References

Take into account this code fragment:

perform addClickHandler(ingredient) {
    ingredient.click on = perform onClick(e) {
        alert("Clicked the " + ingredient.nodeName)
    }
}

Right here, onClick has a closure that retains a reference to ingredient (by way of ingredient.nodeName). By additionally assigning onClick to ingredient.click on, the round reference is created; i.e.: ingredient → onClick → ingredient → onClick → ingredient…

Apparently, even when ingredient is faraway from the DOM, the round self-reference above would stop ingredient and onClick from being collected, and therefore, a reminiscence leak.

Avoiding Reminiscence Leaks: The Necessities

JavaScript’s reminiscence administration (and, specifically, rubbish assortment) is basically primarily based on the notion of object reachability.

The next objects are assumed to be reachable and are often called “roots”:

  • Objects referenced from wherever within the present name stack (that’s, all native variables and parameters within the features at present being invoked, and all of the variables within the closure scope)
  • All world variables

Objects are saved in reminiscence at the least so long as they’re accessible from any of the roots by a reference, or a sequence of references.

There’s a Rubbish Collector within the browser that cleans reminiscence occupied by unreachable objects; in different phrases, objects will probably be faraway from reminiscence if and provided that the GC believes that they’re unreachable. Sadly, it’s pretty simple to finish up with defunct “zombie” objects which are not in use however that the GC nonetheless thinks are “reachable.”

JavaScript Situation #4: Confusion About Equality

One of many conveniences in JavaScript is that it’s going to robotically coerce any worth being referenced in a boolean context to a boolean worth. However there are instances the place this may be as complicated as it’s handy. Among the following, for instance, have been identified to be troublesome for a lot of a JavaScript developer:

// All of those consider to 'true'!
console.log(false == '0');
console.log(null == undefined);
console.log(" trn" == 0);
console.log('' == 0);

// And these do too!
if ({}) // ...
if ([]) // ...

With regard to the final two, regardless of being empty (which could lead one to consider that they’d consider to false), each {} and [] are in reality objects and any object will probably be coerced to a boolean worth of true in JavaScript, according to the ECMA-262 specification.

As these examples reveal, the foundations of kind coercion can generally be clear as mud. Accordingly, except kind coercion is explicitly desired, it’s sometimes greatest to make use of === and !== (reasonably than == and !=), in order to keep away from any unintended unintended effects of kind coercion. (== and != robotically carry out kind conversion when evaluating two issues, whereas === and !== do the identical comparability with out kind conversion.)

And fully as a sidepoint—however since we’re speaking about kind coercion and comparisons—it’s price mentioning that evaluating NaN with something (even NaN!) will at all times return false. You subsequently can’t use the equality operators (==, ===, !=, !==) to find out whether or not a worth is NaN or not. As an alternative, use the built-in world isNaN() perform:

console.log(NaN == NaN);    // False
console.log(NaN === NaN);   // False
console.log(isNaN(NaN));    // True

JavaScript Situation #5: Inefficient DOM Manipulation

JavaScript makes it comparatively simple to control the DOM (i.e., add, modify, and take away components), however does nothing to advertise doing so effectively.

A standard instance is code that provides a collection of DOM Parts separately. Including a DOM ingredient is an costly operation. Code that provides a number of DOM components consecutively is inefficient and sure to not work effectively.

One efficient different when a number of DOM components have to be added is to make use of doc fragments as an alternative, thereby bettering effectivity and efficiency.

For instance:

var div = doc.getElementsByTagName("my_div");
	
var fragment = doc.createDocumentFragment();

for (var e = 0; e < elems.size; e++) {  // elems beforehand set to listing of components
    fragment.appendChild(elems[e]);
}
div.appendChild(fragment.cloneNode(true));

Along with the inherently improved effectivity of this strategy, creating hooked up DOM components is dear, whereas creating and modifying them whereas indifferent after which attaching them yields a lot better efficiency.

JavaScript Situation #6: Incorrect Use of Operate Definitions Inside for Loops

Take into account this code:

var components = doc.getElementsByTagName('enter');
var n = components.size;    // Assume we've 10 components for this instance
for (var i = 0; i < n; i++) {
    components[i].onclick = perform() {
        console.log("That is ingredient #" + i);
    };
}

Primarily based on the above code, if there have been 10 enter components, clicking any of them would show “That is ingredient #10”! It’s because, by the point onclick is invoked for any of the weather, the above for loop can have accomplished and the worth of i will already be 10 (for all of them).

Right here’s how we will right the aforementioned issues with JavaScript to attain the specified conduct:

var components = doc.getElementsByTagName('enter');
var n = components.size;    // Assume we've 10 components for this instance
var makeHandler = perform(num) {  // Outer perform
     return perform() {   // Internal perform
         console.log("That is ingredient #" + num);
     };
};
for (var i = 0; i < n; i++) {
    components[i].onclick = makeHandler(i+1);
}

On this revised model of the code, makeHandler is straight away executed every time we move by the loop, every time receiving the then-current worth of i+1 and binding it to a scoped num variable. The outer perform returns the interior perform (which additionally makes use of this scoped num variable) and the ingredient’s onclick is ready to that interior perform. This ensures that every onclick receives and makes use of the correct i worth (by way of the scoped num variable).

JavaScript Situation #7: Failure to Correctly Leverage Prototypal Inheritance

A surprisingly excessive proportion of JavaScript builders fail to totally perceive, and subsequently to totally leverage, the options of prototypal inheritance.

Right here’s a easy instance. Take into account this code:

BaseObject = perform(identify) {
    if (typeof identify !== "undefined") {
        this.identify = identify;
    } else {
        this.identify="default"
    }
};

Appears pretty easy. Should you present a reputation, use it, in any other case set the identify to ‘default’. For example:

var firstObj = new BaseObject();
var secondObj = new BaseObject('distinctive');

console.log(firstObj.identify);  // -> Leads to 'default'
console.log(secondObj.identify); // -> Leads to 'distinctive'

However what if we had been to do that:

delete secondObj.identify;

We’d then get:

console.log(secondObj.identify); // -> Leads to 'undefined'

However wouldn’t it’s nicer for this to revert to ‘default’? This will simply be performed, if we modify the unique code to leverage prototypal inheritance, as follows:

BaseObject = perform (identify) {
    if(typeof identify !== "undefined") {
        this.identify = identify;
    }
};

BaseObject.prototype.identify="default";

With this model, BaseObject inherits the identify property from its prototype object, the place it’s set (by default) to 'default'. Thus, if the constructor is named with no identify, the identify will default to default. And equally, if the identify property is faraway from an occasion of BaseObject, the prototype chain will then be searched and the identify property will probably be retrieved from the prototype object the place its worth remains to be 'default'. So now we get:

var thirdObj = new BaseObject('distinctive');
console.log(thirdObj.identify);  // -> Leads to 'distinctive'

delete thirdObj.identify;
console.log(thirdObj.identify);  // -> Leads to 'default'

JavaScript Situation #8: Creating Incorrect References to Occasion Strategies

Let’s outline a easy object, and create an occasion of it, as follows:

var MyObject = perform() {}
	
MyObject.prototype.whoAmI = perform() {
    console.log(this === window ? "window" : "MyObj");
};

var obj = new MyObject();

Now, for comfort, let’s create a reference to the whoAmI methodology, presumably so we will entry it merely by whoAmI() reasonably than the longer obj.whoAmI():

var whoAmI = obj.whoAmI;

And simply to make certain every part seems copacetic, let’s print out the worth of our new whoAmI variable:

console.log(whoAmI);

Outputs:

perform () {
    console.log(this === window ? "window" : "MyObj");
}

Okay, cool. Appears superb.

However now, have a look at the distinction once we invoke obj.whoAmI() vs. our comfort reference whoAmI():

obj.whoAmI();  // Outputs "MyObj" (as anticipated)
whoAmI();      // Outputs "window" (uh-oh!)

What went incorrect? After we did the task var whoAmI = obj.whoAmI;, the brand new variable whoAmI was being outlined within the world namespace. Consequently, its worth of this is window, not the obj occasion of MyObject!

Thus, if we actually have to create a reference to an present methodology of an object, we have to you should definitely do it inside that object’s namespace, to protect the worth of this. A method of doing this could be as follows:

var MyObject = perform() {}
	
MyObject.prototype.whoAmI = perform() {
    console.log(this === window ? "window" : "MyObj");
};

var obj = new MyObject();
obj.w = obj.whoAmI;   // Nonetheless within the obj namespace

obj.whoAmI();  // Outputs "MyObj" (as anticipated)
obj.w();       // Outputs "MyObj" (as anticipated)

JavaScript Situation #9: Offering a String because the First Argument to setTimeout or setInterval

For starters, let’s be clear on one thing right here: Offering a string as the primary argument to setTimeout or setInterval is not itself a mistake per se. It’s completely reliable JavaScript code. The problem right here is extra certainly one of efficiency and effectivity. What isn’t defined is that in the event you move in a string as the primary argument to setTimeout or setInterval, it will likely be handed to the perform constructor to be transformed into a brand new perform. This course of will be gradual and inefficient, and isn’t essential.

The choice to passing a string as the primary argument to those strategies is to as an alternative move in a perform. Let’s check out an instance.

Right here, then, can be a reasonably typical use of setInterval and setTimeout, passing a string as the primary parameter:

setInterval("logTime()", 1000);
setTimeout("logMessage('" + msgValue + "')", 1000);

The higher selection can be to move in a perform because the preliminary argument; e.g.:

setInterval(logTime, 1000);   // Passing the logTime perform to setInterval
	
setTimeout(perform() {       // Passing an nameless perform to setTimeout
    logMessage(msgValue);     // (msgValue remains to be accessible on this scope)
}, 1000);

JavaScript Situation #10: Failure to Use “Strict Mode”

As defined in our JavaScript Hiring Information, “strict mode” (i.e., together with 'use strict'; initially of your JavaScript supply recordsdata) is a solution to voluntarily implement stricter parsing and error dealing with in your JavaScript code at runtime, in addition to making it safer.

Whereas, admittedly, failing to make use of strict mode will not be a “mistake” per se, its use is more and more being inspired and its omission is more and more changing into thought of unhealthy kind.

Listed below are some key advantages of strict mode:

  • Makes debugging simpler. Code errors that might in any other case have been ignored or would have failed silently will now generate errors or throw exceptions, alerting you sooner to issues with JavaScript in your codebase and directing you extra shortly to their supply.
  • Prevents unintentional globals. With out strict mode, assigning a worth to an undeclared variable robotically creates a world variable with that identify. This is without doubt one of the most typical JavaScript errors. In strict mode, making an attempt to take action throws an error.
  • Eliminates this coercion. With out strict mode, a reference to a this worth of null or undefined is robotically coerced to the worldwide. This will trigger many irritating bugs. In strict mode, referencing a this worth of null or undefined throws an error.
  • Disallows duplicate property names or parameter values. Strict mode throws an error when it detects a reproduction named property in an object (e.g., var object = {foo: "bar", foo: "baz"};) or a reproduction named argument for a perform (e.g., perform foo(val1, val2, val1){}), thereby catching what is nearly actually a bug in your code that you just may in any other case have wasted plenty of time monitoring down.
  • Makes eval() safer. There are some variations in the way in which eval() behaves in strict mode and in nonstrict mode. Most importantly, in strict mode, variables and features declared inside an eval() assertion are not created within the containing scope. (They are created within the containing scope in nonstrict mode, which will also be a typical supply of issues with JavaScript.)
  • Throws error on invalid use of delete. The delete operator (used to take away properties from objects) can’t be used on nonconfigurable properties of the thing. Nonstrict code will fail silently when an try is made to delete a nonconfigurable property, whereas strict mode will throw an error in such a case.

Mitigating JavaScript Points With a Smarter Strategy

As is true with any know-how, the higher you perceive why and the way JavaScript works and doesn’t work, the extra stable your code will probably be and the extra you’ll be capable to successfully harness the true energy of the language. Conversely, lack of correct understanding of JavaScript paradigms and ideas is certainly the place many JavaScript issues lie.

Totally familiarizing your self with the language’s nuances and subtleties is the simplest technique for bettering your proficiency and rising your productiveness. Avoiding many frequent JavaScript errors will assist when your JavaScript will not be working.


Additional Studying on the Toptal Engineering Weblog:



[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments