Questions
What are the different ways to create an object in JavaScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new feature that needs to create a new object.
You are not sure which of the different ways to create an object in JavaScript you should use.
The Challenge
Explain the different ways to create an object in JavaScript. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might only be aware of one way to create an object, such as using an object literal. They might not be aware of the other ways to create an object or the trade-offs between them.
A senior engineer would be able to provide a detailed explanation of all the different ways to create an object in JavaScript. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in a given situation.
Step 1: Understand the Different Ways to Create an Object
| Method | Description |
|---|---|
| Object Literal | The simplest way to create an object. |
new Keyword | Creates a new object and sets its prototype to the constructor function’s prototype. |
Object.create() | Creates a new object with the specified prototype object and properties. |
class Keyword | Syntactic sugar on top of prototypal inheritance. |
Step 2: Choose the Right Tool for the Job
| Use Case | Recommended Method |
|---|---|
| Creating a simple object | Object Literal |
| Creating an object with a constructor | new Keyword |
| Creating an object with a specific prototype | Object.create() |
| Creating a complex object with methods | class Keyword |
Step 3: Code Examples
Here are some code examples that show the difference between the different approaches:
Object Literal:
const myObject = {
myProperty: 'myValue'
};new Keyword:
function MyClass() {
this.myProperty = 'myValue';
}
const myObject = new MyClass();Object.create():
const myPrototype = {
myMethod() {
console.log('hello');
}
};
const myObject = Object.create(myPrototype);class Keyword:
class MyClass {
constructor() {
this.myProperty = 'myValue';
}
myMethod() {
console.log('hello');
}
}
const myObject = new MyClass(); Practice Question
You want to create a new object that inherits from another object. Which of the following would you use?