W3docs

JavaScript new Operator

Learn how JavaScript constructor functions and the new operator create objects: what new does step by step, the return-value rule, new.target.

Introduction to Constructors and the new Operator

In JavaScript, constructors are functions designed to initialize newly created objects. They play a pivotal role in object-oriented programming by allowing developers to define properties and behaviors that objects of a certain class should have. The new operator is used to create an instance of an object based on a constructor function, setting up a fresh object environment based on the specified prototype and running the constructor to initialize the new object.

How Constructors Work

A constructor function in JavaScript looks like any other function, but it is conventionally named with a capital letter to distinguish it from regular functions. When the new operator invokes a constructor function, four things happen behind the scenes, roughly equivalent to this pseudo-code:

function User(name) {
  // this = {};  (1) an empty object is created and assigned to this
  // this.__proto__ = User.prototype;  (2) prototype is linked

  this.name = name;  // (3) the constructor body runs, adding properties to this

  // return this;  (4) this is returned automatically
}
  1. A new empty object is created and assigned to this.
  2. The prototype is linked: the new object's internal [[Prototype]] is set to the constructor's prototype property, so it inherits properties and methods defined there.
  3. The constructor body runs: the function executes with the arguments you pass, and this refers to the brand-new object, so assignments like this.name = name attach properties to it.
  4. The object is returned: this is returned automatically unless the constructor explicitly returns a different object (see The return-value rule below).
Info

Modern JavaScript uses the class syntax to define constructors and methods more intuitively. This provides a more straightforward, class-based approach similar to other programming languages.

Example: Basic Constructor Function

javascript— editable

Explanation: In this example, User is a constructor function that initializes name, age, and a greet method on newly created objects. The new User('John', 30) statement creates a new instance of User with the name "John" and age 30. Inside greet, this refers to the object the method was called on.

The return-value rule

Constructors normally don't use return — the new object (this) comes back automatically. But return does have a special, easy-to-miss behavior inside a constructor:

  • If return is followed by an object, that object is returned instead of this.
  • If return is followed by a primitive (string, number, boolean, undefined, etc.), it is ignored and this is returned as usual.
javascript— editable

Explanation: WithObject returns a plain object, so that object replaces the instance entirely. WithPrimitive returns a string, which is ignored, so the original this (with name: 'Alice') is returned. You'll rarely rely on this, but it explains surprising results when a constructor accidentally returns a value.

Detecting new with new.target

Inside any function, new.target is undefined when the function is called normally and equal to the function itself when called with new. This lets a constructor detect how it was invoked — useful for enforcing (or silently allowing) the new keyword.

javascript— editable

Explanation: Because Modal checks new.target, calling Modal('Without new') without new is transparently forwarded to new Modal(...), so b is still a real Modal instance. (Note: many teams prefer to not do this and let a missing new fail loudly instead.)

When would I use a constructor?

Use a constructor function (or a class) when you need to create many objects of the same shape — multiple users, cars, DOM widgets, etc. The constructor centralizes the setup logic so every instance is built the same way and shares methods through the prototype.

If you only need a single object, a plain object literal { ... } is simpler. For a one-off object that still benefits from a constructor body, you can even use an anonymous constructor:

javascript— editable

Explanation: The anonymous function runs once as a constructor and is not saved anywhere, so it can't be reused — it's just a way to encapsulate complex one-time setup.

Constructor functions vs. classes

Modern code usually prefers the class syntax, which is essentially syntactic sugar over constructor functions and prototypes. The two snippets below are equivalent:

javascript— editable

Classes add real benefits over constructor functions: methods are non-enumerable by default, the body runs in strict mode, calling a class without new throws an error, and extends/super make inheritance far cleaner. Constructor functions remain important to understand because classes are built on the same prototype mechanism, and you'll still meet them in older code.

Using Constructors for Complex Objects

Constructors can be used to set up more complex relationships between objects, including methods that interact with other properties of the objects.

Example: Constructor with Methods

javascript— editable

Explanation: The Car constructor sets up each car object with specific properties and a method that displays information about the car.

Example: Prototype Methods

javascript— editable

Explanation: By adding introduce to the Employee prototype, all instances share the same method, which is more memory-efficient than defining it directly in the constructor.

Warning

It's recommended to use ES6 classes for defining objects and constructors for cleaner and more readable code.

Best Practices with Constructors

When working with constructors in JavaScript, adhering to certain best practices can greatly improve the readability, efficiency, and scalability of your code. Below, the practices are elaborated on with detailed examples and explanations:

1. Naming Convention

Best Practice: Always start constructor names with a capital letter to differentiate them from regular functions. This is a common convention in JavaScript and many other programming languages that helps developers quickly identify constructor functions.

Example:

javascript— editable

Explanation: The constructor function Laptop starts with a capital letter, indicating that it is intended to be used with the new operator to create new objects.

2. Separate Logic

Best Practice: For methods that do not require access to individual instance data, define them on the constructor's prototype rather than within the constructor itself. This approach saves memory because all instances share the same method rather than each instance creating a new function in memory.

Example:

javascript— editable

Explanation: The describe method is added to the Book prototype, meaning all instances of Book share the same describe method. This is more efficient than if describe were defined inside the constructor, which would result in a new function for every book instance.

3. Return Values

Best Practice: Avoid returning values from constructors. JavaScript constructors automatically return the new object instance unless explicitly returning a different object. Returning non-object values (like a string or a number) will have no effect, and the new instance will still be returned.

Example:

javascript— editable

Explanation: Despite attempting to return a string from the Player constructor, JavaScript ignores this return value because it's not an object. The new Player instance is returned as expected.

Conclusion

Understanding and utilizing constructors and the new operator in JavaScript is essential for effective object-oriented programming. By following the conventions and best practices outlined here, developers can create organized, efficient, and scalable code. Constructors provide a powerful mechanism for initializing new objects and defining their behavior in a structured and intuitive manner.

To go deeper, explore how constructors share behavior through prototypal inheritance, how the class syntax builds on these ideas, and how a function is also an object with its own properties.

Practice

Practice
What occurs when a function is executed with 'new' in JavaScript?
What occurs when a function is executed with 'new' in JavaScript?
Was this page helpful?