DEV Community

Sleepless Yogi
Sleepless Yogi

Posted on

Interview Question: What is the difference between the `new` operator and `Object.create` Operator in JavaScript

new Operator

  • This is used to create an object from a constructor function
  • The new keywords also execute the constructor function
function Car() {
  console.log(this) // this points to myCar
  this.name = "Honda";
}

var myCar = Object.create(Car)
console.log(myCar) // Car {name: "Honda", constructor: Object}
console.log(myCar.name) // Honda
console.log(myCar instanceof Car) // true
console.log(myCar.constructor) // function Car() {}
console.log(myCar.constructor === Car) // true
console.log(typeof myCar) // object

Enter fullscreen mode Exit fullscreen mode

Object.create

  • You can also use Object.create to create a new object
  • But, it does not execute the constructor function
  • Object.create is used to create an object from another object
const Car = {
  name: "Honda"
}

var myCar = Object.create(Car)
console.log(myCar) // Object {}
console.log(myCar.name) // Honda
console.log(myCar instanceof Car) // ERROR
console.log(myCar.constructor) // Anonymous function object
console.log(myCar.constructor === Car) // false
console.log(typeof myCar) // object

Enter fullscreen mode Exit fullscreen mode

More JavaScript Lessons(from my blog):

Most Frequently Asked JavaScript Interview Questions
Super powerful JavaScript tips & tricks - Part 2
JavaScript Quiz: How well do you know JavaScript?

Top comments (1)

Collapse
 
faisalawanisee profile image
Faisal Awan

Thanks