Skip to main content

The "new" Operator

Objects the Basics: The "new" Operator



What is the new Operator used for in JavaScript?

View Answer:
Interview Response: The new "operator" in JavaScript creates a new object instance from a constructor function, invoking the function with the provided arguments and setting its prototype.

Code Example:

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

// Creating instances using the new operator
const person1 = new Person('John', 30);
const person2 = new Person('Jane', 25);

console.log(person1); // Output: Person { name: 'John', age: 30 }
console.log(person2); // Output: Person { name: 'Jane', age: 25 }

What is the difference between a regular function and a constructor function?

View Answer:
Interview Response: A regular function performs a task, while a constructor function initializes a new object instance with properties and methods, using the "new" keyword.

Code Example:

function User(name) {
this.name = name;
this.isAdmin = false;
}

let user = new User('Jack');

console.log(user.name); // Jack
console.log(user.isAdmin); // false

What steps are taken by a constructor function when it gets invoked in relation to the "this" keyword?

View Answer:
Interview Response: A constructor function, upon invocation, creates an empty object, assigns this empty object to 'this', adds properties and methods via 'this', and implicitly returns 'this'.

Code Example:

function User(name) {
// this = {}; (implicitly)

// add properties to this
this.name = name;
this.isAdmin = false;

// return this; (implicitly)
}

// So let user = new User("Jack") gives the same result as:

let user = {
name: 'Jack',
isAdmin: false,
};

// another example
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
// 'this' is implicitly returned
}

let myCar = new Car('Toyota', 'Corolla', 2005);

What is the primary function of constructor functions?

View Answer:
Interview Response: The primary function of constructor functions is to initialize new object instances with specific properties and methods, establishing their structure and behavior.

What is the result when using an arrow function as a constructor?

View Answer:
Interview Response: Using an arrow function as a constructor is not possible because arrow functions have no "this" binding and cannot be used with the "new" keyword, resulting in a TypeError.

Technical Response: Any attempt to resolve "this" in an arrow function results in a type error. This behavior is especially notable when you try to use an arrow function as a constructor, resulting in a type error. A cardinal rule to remember in JavaScript development is that arrow functions have no "THIS".

Code Example:

const Car = (color) => {
this.color = color;
};

const redCar = new Car('red'); // TypeError: Car is not a constructor

Can you omit the parentheses when you invoke a constructor function?

View Answer:
Interview Response: Technically, Yes, when you have no arguments and this approach is permitted by the specification but not considered a good style. It would be best always to use the parentheses even when you have no arguments in your constructor.

Code Example:

// let user = new User; <-- no parentheses

// same as
let user = new User(); // <-- proper implementation

What are the explicit rules on return statements in constructor functions?

View Answer:
Interview Response: Constructors automatically return this (the new object). If you explicitly return an object, that's returned instead. Non-object explicit returns are ignored, this is returned.

Technical Response: Constructors often do not contain a return statement. Their role is to enter all relevant information into this, and it immediately becomes the outcome; nevertheless, if there is a return statement, the rule is straightforward.

  1. If the return function gets used with an object, the object is returned instead of this.
  2. If the return function gets invoked with a primitive, it gets ignored.

Code Example:

function BigUser() {
this.name = 'John';

return { name: 'Godzilla' }; // <-- returns this object
}

console.log(new BigUser().name); // Godzilla, got that object

What happens if a constructor function is called without the "new" operator?

View Answer:
Interview Response: If a constructor is called without "new", "this" is not bound to the newly created object, it refers to the global or outer function scope, which can cause unintended side effects.

Code Example:

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

var myCar = Car('Toyota', 'Corolla', 2005); // 'this' not bound to a new object

console.log(myCar); // Outputs: undefined

console.log(window.make); // Outputs: 'Toyota', if in a browser environment

How can you check if an object was created by a specific constructor?

View Answer:
Interview Response: You can use the `instanceof` operator in JavaScript. For example, if `obj` was created by `Constructor`, check with `obj instanceof Constructor`. It returns `true` if `obj` was created by `Constructor`.

Code Example:

function MyConstructor() {
// Constructor logic here
}

let obj = new MyConstructor();

if (obj instanceof MyConstructor) {
console.log('obj was created by MyConstructor');
} else {
console.log('obj was not created by MyConstructor');
}