Skip to main content

Command Palette

Search for a command to run...

The new Keyword in JavaScript

Updated
8 min read
The new Keyword in JavaScript

JavaScript new keyword is used to create an instance of an object that has a constructor function.

On calling the constructor function with the 'new' operator, the following actions are taken:

  • A new empty object is created.

  • The new object’s internal 'Prototype' property (__proto__) is set the same as the prototype of the constructing function.

  • The 'this' variable is made to point to the newly created object. It binds the property that is declared with the 'this' keyword to the new object.

  • About the returned value, there are three situations below.

 

Syntax:

new constructorFunction(arguments);

Parameters:

  • ConstructorFunction: A class or function that specifies the type of the object instance.

  • Arguments: A list of values that the constructor will be called with.

Return Value:

  • If the constructor function returns a non-primitive value (Object, array, etc), the constructor function still returns that value. Which means the new operator won't change the returned value.

  • If the constructor function returns nothing, 'this' is returned;

  • If the constructor function returns a primitive value,  it will be ignored, and 'this' is returned.

Example 1: This example shows the use of a new keyword.

function Fruit(color, taste, seeds) {
    this.color = color;
    this.taste = taste;
    this.seeds = seeds;
}
// Create an object
const fruit1 = new Fruit('Yellow', 'Sweet', 1);
// Display the result
console.log(fruit1.color);

Output:

Yellow

Explanation: In the above example, the 'new' keyword creates an empty object. Here, Fruit() includes three properties 'color', 'taste', and 'seeds' that are declared with 'this' keyword. So, a new empty object will now include all these properties i.e. 'color', 'taste' and 'seeds'. The newly created objects are returned as fruit1().

Example 2: This example shows the use of a new keyword.

function func() {
    let c = 1;
    this.a = 100;
}
// Set the function prototype
func.prototype.b = 200;
// Create an object
let obj = new func();
// Display the result on console
console.log(obj.a);
console.log(obj.b);

Output:

100 
200

Explanation: In the above example, the 'new' keyword creates an empty object and then sets the 'prototype' property of this empty object to the prototype property of func(). New property 'b' is assigned using func.prototype.y. So, the new object will also include 'b' property. Then it binds all the properties and functions declared with this keyword to a new empty object. Here, func() includes only one property 'a' which is declared with this keyword. So new empty object will now include 'a' property. The func() also includes 'c' variable which is not declared with this keyword. So 'c' will not be included in new object. Lastly, the newly created object is returned. Note that func() does not include areturn statement. The compiler will implicitly insert 'return this' at the end.

Description

When a function is called with the new keyword, the function will be used as a constructor. new will do the following things:

  1. Creates a blank, plain JavaScript object. For convenience, let's call it newInstance.

  2. Points newInstance's [[Prototype]] to the constructor function's prototype property, if the prototype is an Object. Otherwise, newInstance stays as a plain object with Object.prototype as its [[Prototype]].

  3. Executes the constructor function with the given arguments, binding newInstance as the this context (i.e., all references to this in the constructor function now refer to newInstance).

  4. If the constructor function returns a non-primitive, this return value becomes the result of the whole new expression. Otherwise, if the constructor function doesn't return anything or returns a primitive, newInstance is returned instead. (Normally constructors don't return a value, but they can choose to do so to override the normal object creation process.)

Classes can only be instantiated with the new operator — attempting to call a class without new will throw a TypeError.

Creating an object with a user-defined constructor function requires two steps:

Define the object type by writing a function that specifies its name and properties. For example, a constructor function to create an object Foo might look like this:

function Foo(bar1, bar2) {
  this.bar1 = bar1;
  this.bar2 = bar2;
}

Create an instance of the object with new.

const myFoo = new Foo("Bar 1", 2021);

You can always add a property to a previously defined object instance. For example, the statement car1.color = "black" adds a property color to car1, and assigns it a value of "black".

However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the constructor's prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value "original color" to all objects of type Car, and then overwrites that value with the string "black" only in the instance object car1. For more information, see prototype.

function Car() {}
const car1 = new Car();
const car2 = new Car();

console.log(car1.color); // undefined

Car.prototype.color = "original color";
console.log(car1.color); // 'original color'

car1.color = "black";
console.log(car1.color); // 'black'

console.log(Object.getPrototypeOf(car1).color); // 'original color'
console.log(Object.getPrototypeOf(car2).color); // 'original color'
console.log(car1.color); // 'black'
console.log(car2.color); // 'original color'

A function can know whether it is invoked with new by checking new.target. new.target is only undefined when the function is invoked without new. For example, you can have a function that behaves differently when it's called versus when it's constructed:

Copy function Car(color) { if (!new.target) { // Called as function. return ${color} car; } // Called with new. this.color = color; }

const a = Car("red"); // a is "red car" const b = new Car("red"); // b is Car { color: "red" }

  • Array(), Error(), and Function() behave the same when called as a function or a constructor.

  • Boolean(), Number(), and String() coerce their argument to the respective primitive type when called, and return wrapper objects when constructed.

  • Date() returns a string representing the current date when called, equivalent to new Date().toString().

After ES6, the language is stricter about which are constructors and which are functions. For example:

  • Symbol() and BigInt() can only be called without new. Attempting to construct them will throw a TypeError.

  • Proxy and Map can only be constructed with new. Attempting to call them will throw a TypeError.

Examples

Object type and object instance

Suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

jsCopy

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

Now you can create an object called myCar as follows:

jsCopy

const myCar = new Car("Eagle", "Talon TSi", 1993);

This statement creates myCar and assigns it the specified values for its properties. Then the value of myCar.make is the string "Eagle", myCar.year is the integer 1993, and so on.

You can create any number of car objects by calls to new. For example:

const kensCar = new Car("Nissan", "300ZX", 1992);

Object property that is another itself

Suppose you define an object called Person as follows:

function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}

And then instantiate two new Person objects as follows:

const rand = new Person("Rand McNally", 33, "M");
const ken = new Person("Ken Jones", 39, "M");

Then you can rewrite the definition of Car to include an owner property that takes a Person object, as follows:

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
}

To instantiate the new objects, you then use the following:

const car1 = new Car("Eagle", "Talon TSi", 1993, rand);
const car2 = new Car("Nissan", "300ZX", 1992, ken);

Instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the parameters for the owners. To find out the name of the owner of car2, you can access the following property:

car2.owner.name;

Using new with classes

class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const p = new Person("Caroline");
p.greet(); // Hello, my name is Caroline