Class Constructor cannot be invoked without 'new' in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Class Constructor cannot be invoked without 'new' #

The "Class constructor cannot be invoked without 'new'" error occurs for 2 reasons:

  1. Trying to instantiate a class without using the new operator.
  2. Forgetting to extend the Component class in a React.js application.

class constructor cannot be invoked without new

Here is an example of how the error occurs.

index.js
class Person { constructor(first, last) { this.first = first; this.last = last; } getName() { return `${this.first} ${this.last}`; } } // ⛔️ Class constructor Person cannot be invoked without 'new' const p1 = Person('James', 'Doe');

To solve the "Class constructor cannot be invoked without 'new'" error, use the new operator when instantiating the class. The new operator allows us to create an instance of a class.

index.js
class Person { constructor(first, last) { this.first = first; this.last = last; } getName() { return `${this.first} ${this.last}`; } } // 👇️ use `new` operator const p1 = new Person('James', 'Doe'); console.log(p1); // 👉️ {first: 'James', last: 'Doe'} console.log(p1.getName()); // 👉️ "James Doe"

We used the new operator upon class instantiation. The new operator does 3 things:

  1. Creates a new object that inherits the prototype of the class.
  2. Calls the constructor function with the provided parameters and binds the this keyword to the newly created object.
  3. Returns the newly created object.

If you got the error inside of a React.js application, you most likely forgot to extend from the Component class.

App.js
import React from 'react'; // ⛔️ Class constructor App cannot be invoked without 'new' class App { render() { return <div>Example</div>; } } export default App;

To solve the "Class constructor cannot be invoked without 'new'" error, extend the Component class when defining a class in a React.js application, e.g. class App extends React.Component {}.

App.js
import React from 'react'; // ✅ Now extending Component class class App extends React.Component { render() { return <div>Example</div>; } } export default App;

The extends keyword allows us to specify that the App class is a child of the Component class. In other words, App is a subclass of Component.

Use the search field on my Home Page to filter through my more than 3,000 articles.