Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Working With JavaScript Classes: 3 Mistakes to Avoid

DZone's Guide to

Working With JavaScript Classes: 3 Mistakes to Avoid

In this post, we take a look at three common mistakes that programmers make when working with JavaScript classes, and how to avoid them.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

JavaScript classes are important for making developers write less and cleaner code. The classes were introduced in ECMAScript 2015 (ES6) and offer a syntactic sugar over the programming language’s prototype-oriented inheritance.

Benhartouz, who has more than three years of front-end web development experience and uses practical projects to assist developers in advancing their skills, says that “classes are important because they provide a way of writing enjoyable code when creating JavaScript objects and addressing inheritance issues.”

However, most developers do not know how JavaScript classes operate and often make mistakes that lead to bugs in their applications.

In this article, I’m going to talk about three common mistakes that programmers make when working with JavaScript classes.

1. Hoisting Issues

Although JavaScript classes are considered as ‘special functions,’ they sometimes do not behave the same way as normal functions do.

For example, one way to define a JavaScript class is using a class declaration—just like you’d use a function declaration.

Here is an example of how you can use the classkeyword together with the name of the class (“Liveedu” here) to declare a class:

class Liveedu {

      constructor(watch, learn) {

    this.watch = watch;

    this.learn = learn;

  }

}

A significant distinction between function declarations and class declarations is that the former are hoisted while the latter are not. Hoisting refers to JavaScript’s inherent characteristic where every declaration is moved to the top of the present scope.

Therefore, you need to declare your class before trying to use it; otherwise, your code may not work.

For example, the following code will give a ReferenceError on the Chrome developer console (showing that a non-existing variable has been referenced).

const student = new Liveedu();

class Liveedu {};

//Uncaught ReferenceError: Liveedu is not defined

Even if you define a class using other methods, you should always be cautious of the hoisting issues in JavaScript classes.

2. Strict Mode Issues

The strict mode directive was introduced in ES5 to specify that the responsible JavaScript code should be run in “strict mode.”

Strict mode removes some JavaScript silent errors by converting them to throw errors and solves inconsistencies to ensure that the JavaScript engines achieve increased optimizations.

In JavaScript, the body of the classes (the section in curly brackets {}) is executed in strict mode. The constructor method, static method, prototype method, as well as other functions, are run in strict mode.

Therefore, any syntax not allowed in strict mode will lead to errors.

For example, another way to declare a JavaScript class is by using a class expression.

Here is an example of a named class expression that will throw an error:

let Liveedu = class Liveedu2 {

  constructor(watch, watch) {

this.watch = watch;

this.watch = watch;

  }

};

console.log(Liveedu.name);

// Duplicate parameter name not allowed in this context

If you run the above code, you’ll get an error indicating that duplicating a parameter name is not permitted. This error occurs because of the body of JavaScript classes are executed in strict mode. 

3. Subclassing Issues

If you want to make a class into a subclass of another class, you’ll need to use the extends keyword.

Here is an example that illustrates how subclasses can be created.

class Liveedu {

  constructor(learn) {

this.learn = learn;

  }

watch() {

console.log(this.learn + ' taught coding skills.');

  }//note that there is no comma here

}

class Student extends Liveedu {

  constructor(learn) {

super(learn); // super class constructor is called and passed in the learn parameter

  }

 watch() {

console.log(this.learn + ' learns new skills.');

  }

}

let learner = new Student('Alfrick');

learner.watch(); // Alfrick learns new skills.

Note that if a constructor method is included in the subclass, you’ll need to first call super() before using the thiskeyword. Otherwise, the code may not work.

Furthermore, you will get an error if you make the mistake of allowing JavaScript classes to extend regular (non-constructible) objects.

The best way to safely inherit from a regular object is to use the Object.setPrototypeOf() method.

Here is an example:

const Liveedu = {
  watch() {
console.log(this.learn + ' learns new skills.');
  }
};

class Student {
  constructor(learn) {
this.learn = learn;
  }
}
// failing to do this will result in a TypeError when you invoke watch

Object.setPrototypeOf(Student.prototype, Liveedu);

let learner = new Student('Alfrick');

learner.watch(); // Alfrick learns new skills.

Conclusion

JavaScript ES6 classes give you a useful technique for creating object-oriented code. However, if you do not understand the little twists and turns in their usage, you may end up with subtle bugs in your application that can cause you unnecessary headaches.

I hope that this article will assist you in overcoming some of the common mistakes that occur when using JavaScript classes.

Is there anything you’d wish to add?

Please let me know in the comment section below.

Happy coding!

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

Topics:
javascript ,classes ,es6 ,web dev ,front-end development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}