Top JavaScript Interview Questions

Enjoy 35% off for first-time user! Join the Discord to claim your coupon!

We have digitized the content of this article and trained it into our AIHirely Interview Assistant. You can click the icon in the upper left corner to visit our product homepage. AIHirely is a real-time AI interview assistant that provides AI-generated reference answers to interviewers’ questions during live interviews. Additionally, you can use our AI Mock Interview feature for in-depth practice sessions tailored to your target job position and resume.

Question: How do you create a new object in JavaScript?

Answer:

In JavaScript, there are several ways to create new objects. Here are the most common methods:


1. Using Object Literal Syntax: This is the most straightforward and commonly used way to create a new object. Example:

const person = {
  name: 'John',
  age: 30,
  greet: function() {
    console.log('Hello, ' + this.name);
  }
};

console.log(person.name);  // John
person.greet();            // Hello, John
  • The object is created using {} (curly braces), where you define key-value pairs.

  • This method is ideal for creating simple, static objects.


2. Using the new Object() Syntax: This is a more verbose way to create an empty object and then assign properties to it. It’s rarely used but still a valid approach. Example:

const person = new Object();
person.name = 'John';
person.age = 30;
person.greet = function() {
  console.log('Hello, ' + this.name);
};

console.log(person.name);  // John
person.greet();            // Hello, John
  • The new Object() syntax creates an empty object, and then you can add properties to it.

3. Using a Constructor Function: Constructor functions are special functions designed to create and initialize objects. They are commonly used for creating multiple objects with similar properties and methods. Example:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log('Hello, ' + this.name);
  };
}

const person1 = new Person('John', 30);
const person2 = new Person('Jane', 25);

console.log(person1.name);  // John
console.log(person2.age);   // 25
person1.greet();            // Hello, John
  • The function Person is a constructor function, and new Person() creates a new instance of the Person object. Constructor functions are useful for creating multiple instances of an object with similar properties.

4. Using Object.create() Method: Object.create() is used to create a new object and set its prototype to the specified object. This method is useful if you want to create an object that inherits from another object.Example:

const personPrototype = {
  greet: function() {
    console.log('Hello, ' + this.name);
  }
};

const person = Object.create(personPrototype);
person.name = 'John';
person.age = 30;

console.log(person.name);  // John
person.greet();            // Hello, John
  • Object.create() creates a new object and allows you to set a custom prototype (in this case, personPrototype).

  • This is particularly useful when dealing with inheritance.


5. Using the ES6 Class Syntax (Introduced in ES6): Classes in JavaScript provide a cleaner syntax for creating constructor functions and are used to define objects with properties and methods. Example:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log('Hello, ' + this.name);
  }
}

const person1 = new Person('John', 30);
const person2 = new Person('Jane', 25);

console.log(person1.name);  // John
person2.greet();            // Hello, Jane
  • class syntax provides a more modern and object-oriented way to define and create objects.

  • The constructor method is a special function that is called when a new instance of the class is created with the new keyword.


6. Using a Factory Function (Alternative to Classes): A factory function is a regular function that returns an object. Unlike constructor functions, they do not require the new keyword and provide a flexible way to create objects.Example:

function createPerson(name, age) {
  return {
    name: name,
    age: age,
    greet: function() {
      console.log('Hello, ' + this.name);
    }
  };
}

const person1 = createPerson('John', 30);
const person2 = createPerson('Jane', 25);

console.log(person1.name);  // John
person2.greet();            // Hello, Jane
  • Factory functions are a simple and flexible alternative to using constructor functions or classes. They allow you to create multiple objects without using the new keyword.

Summary of Methods to Create Objects:

  1. Object Literal Syntax : The most common and concise way to create an object. { key: value }

  2. new Object() : A less common, more verbose way to create an empty object.

  3. Constructor Functions : A way to create multiple instances of objects using functions, which is commonly used for object-oriented design.

  4. Object.create() : Used to create an object with a specific prototype, useful for inheritance.

  5. ES6 Classes : A modern, class-based approach to creating objects and managing inheritance.

  6. Factory Functions : Functions that return objects, an alternative to using classes or constructor functions.

Each method has its use cases, and the choice of which to use depends on the specific requirements of the application.

Question: How can you clone an object in JavaScript?

Answer:

Cloning an object in JavaScript means creating a copy of an object so that changes to the new object do not affect the original one. There are multiple ways to clone objects, and the choice of method depends on whether you need a shallow copy (copies the top-level properties) or a deep copy (copies nested objects as well). Below are the most common methods for cloning objects:


1. Using Object.assign() (Shallow Clone) Object.assign() is used to copy the values of all enumerable properties from one or more source objects to a target object. It performs a shallow copy , meaning if the original object has nested objects, they are not cloned but referenced.Example:

const original = {
  name: 'John',
  age: 30,
  address: { city: 'New York', zip: '10001' }
};

const clone = Object.assign({}, original);

console.log(clone);  // { name: 'John', age: 30, address: { city: 'New York', zip: '10001' } }
clone.address.city = 'Los Angeles';
console.log(original.address.city);  // 'Los Angeles' (shallow copy: nested object is shared)
  • The shallow copy means that the address object inside the original and clone is still a reference to the same object. Changing properties inside nested objects will affect both.

2. Using the Spread Operator (Shallow Clone) The spread operator (...) is another way to clone an object in a concise manner. Like Object.assign(), it creates a shallow copy of the object.Example:

const original = {
  name: 'John',
  age: 30,
  address: { city: 'New York', zip: '10001' }
};

const clone = { ...original };

console.log(clone);  // { name: 'John', age: 30, address: { city: 'New York', zip: '10001' } }
clone.address.city = 'Los Angeles';
console.log(original.address.city);  // 'Los Angeles' (shallow copy: nested object is shared)
  • The spread operator also creates a shallow copy. Nested objects are still references to the original.

3. Using JSON.parse() and JSON.stringify() (Deep Clone) If you need to clone an object with nested objects (a deep copy ), you can use JSON.parse() and JSON.stringify() to serialize the object into a JSON string and then deserialize it back into a new object. This method performs a deep copy, but it has some limitations (e.g., it does not clone functions or special objects like Date, RegExp, Map, Set, etc.).Example:

const original = {
  name: 'John',
  age: 30,
  address: { city: 'New York', zip: '10001' }
};

const clone = JSON.parse(JSON.stringify(original));

console.log(clone);  // { name: 'John', age: 30, address: { city: 'New York', zip: '10001' } }
clone.address.city = 'Los Angeles';
console.log(original.address.city);  // 'New York' (deep copy: nested object is cloned)
  • This method creates a deep copy. Changes to the nested object in clone do not affect the original original object. Limitations:

  • It cannot clone functions, undefined, Infinity, NaN, Date objects, RegExp objects, and Map/Set instances properly.

  • It also does not handle circular references.


4. Using a Custom Function for Deep Cloning (Manual Deep Copy) For more control over the cloning process, you can write a custom function that recursively clones nested objects. This way, you can handle more complex structures (like functions, Date, RegExp, etc.).Example:

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;

  // Handle Date object
  if (obj instanceof Date) return new Date(obj);

  // Handle Array
  if (Array.isArray(obj)) {
    return obj.map(item => deepClone(item));
  }

  // Handle Object
  const clonedObj = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key]);
    }
  }
  return clonedObj;
}

const original = {
  name: 'John',
  age: 30,
  address: { city: 'New York', zip: '10001' },
  birthDate: new Date('1993-05-15')
};

const clone = deepClone(original);

console.log(clone);
clone.address.city = 'Los Angeles';
console.log(original.address.city);  // 'New York' (deep copy: nested object is cloned)
console.log(clone.birthDate instanceof Date); // true
  • This function performs a deep copy and can handle objects, arrays, and special types like Date.

5. Using Libraries (e.g., Lodash’s _.cloneDeep) For more robust and optimized deep cloning, you can use external libraries like Lodash, which provides the _.cloneDeep() method to deeply clone objects, handling edge cases and special types.Example with Lodash:

// First, install Lodash via npm or include it in your project
// npm install lodash

const _ = require('lodash');

const original = {
  name: 'John',
  age: 30,
  address: { city: 'New York', zip: '10001' },
  birthDate: new Date('1993-05-15')
};

const clone = _.cloneDeep(original);

console.log(clone);
clone.address.city = 'Los Angeles';
console.log(original.address.city);  // 'New York' (deep copy)
console.log(clone.birthDate instanceof Date); // true
  • _.cloneDeep() from Lodash handles deep cloning efficiently and works with all types (including Date, RegExp, and other complex structures).

Summary:

  • Shallow Cloning : Copies only the top-level properties, leaving references to nested objects. Methods: Object.assign(), Spread operator (...).

  • Deep Cloning : Copies the object along with all nested objects. Methods: JSON.parse() / JSON.stringify(), custom deep copy function, or _.cloneDeep() from Lodash.

  • Choosing the Right Method : Use shallow cloning when you don’t need to clone nested objects or if performance is a priority. Use deep cloning when dealing with objects that contain nested objects or special objects that need to be cloned fully.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as JavaScript interview questions, JavaScript interview experiences, and details about various JavaScript job positions. Click here to check it out.

Share:

Get Started with the Best AI Interview Assistant

Unlock your full potential with AIhirely! Start today and let the best AI job interview assistant help you practice, refine, and succeed.

Get Started Now