Explorer
JavaScript

objects

Objects are one of the most important data structures in JavaScript.

Almost everything in JavaScript that represents a complex entity can be modeled using objects: users, products, API responses, application settings, and even functions.

But JavaScript objects have some interesting behaviors.

For example:

  • Why can two different objects have the same properties but still be unequal?

  • Why does changing one object sometimes affect another variable?

  • What happens when we use an object as another object's property key?

  • What is the difference between shallow copy and deep copy?

  • How does JavaScript handle object destructuring and spreading?

Let's explore these concepts through practical examples and interview questions.


1. Understanding Objects

An object is a collection of properties, where each property consists of a key and a value.

JAVASCRIPT
const user = {
  name: "Piyush",
  age: 24,
  isDeveloper: true
};

Here:

  • name, age, and isDeveloper are property keys.

  • "Piyush", 24, and true are their corresponding values.

We can access object properties in two ways.

Dot notation:

JAVASCRIPT
console.log(user.name); // Piyush

Bracket notation:

JAVASCRIPT
console.log(user["age"]); // 24

Bracket notation is especially useful when the property name is stored inside a variable.

Computed Properties

What if we want to dynamically create an object property?

JAVASCRIPT
const property = "firstName";
const name = "Piyush Agarwal";

const person = {
  [property]: name
};

console.log(person);

Output:

JAVASCRIPT
{
  firstName: "Piyush Agarwal"
}

The square brackets allow JavaScript to evaluate the variable and use its value as the property name.

Without square brackets:

JAVASCRIPT
const person = {
  property: name
};

The property would literally be named property, not firstName.

Looping Through Objects

We can use for...in to iterate over an object's enumerable property keys.

JAVASCRIPT
const user = {
  name: "Piyush",
  age: 24
};

for (const key in user) {
  console.log(key);
  console.log(user[key]);
}

Output:

JAVASCRIPT
name
Piyush
age
24

Notice that we use user[key] instead of user.key.

Why?

Because key is a variable containing the property name.

Using user.key would look for a property literally named "key".


2. Object Interview Questions

Question 1: What happens when we use the delete keyword on a function parameter?

JAVASCRIPT
const func = (function (a) {
  delete a;
  return a;
})(5);

console.log(func);
JAVASCRIPT
Output: 5

Explanation:

The delete operator is used to remove properties from objects.

Here, a is a function parameter, not an object property.

Therefore, delete a does not delete the local parameter.

The value remains 5.

Remember:

JAVASCRIPT
const user = {
  name: "Piyush",
  age: 24
};

delete user.age;

console.log(user);
// { name: "Piyush" }

The delete operator removes configurable object properties. It does not remove local variables or function parameters.

Question 2: What happens when an object contains duplicate property names?

JAVASCRIPT
const obj = {
  a: "one",
  b: "two",
  a: "three"
};

console.log(obj);

Output:

JAVASCRIPT
{
  a: "three",
  b: "two"
}

Explanation:

JavaScript allows duplicate property definitions in object literals.

When the same property is defined multiple times, the last definition determines its final value.

Here, a is initially assigned "one" and then overwritten with "three".

Question 3: Multiply all numeric property values by 2.

Consider the following object:

JAVASCRIPT
const nums = {
  a: 100,
  b: 200,
  title: "My nums"
};

Write a function that multiplies all numeric property values by 2 without modifying string values.

Solution:

JAVASCRIPT
function multiplyByTwo(obj) {
  for (const key in obj) {
    if (typeof obj[key] === "number") {
      obj[key] *= 2;
    }
  }
}

multiplyByTwo(nums);

console.log(nums);

Output:

JAVASCRIPT
{
  a: 200,
  b: 400,
  title: "My nums"
}

Explanation:

  1. We iterate through all enumerable properties.

  2. We check the type of each property using typeof.

  3. If the value is a number, we multiply it by 2.

  4. Other property values remain unchanged.

Notice that this function modifies the original object.

Question 4: What happens when objects are used as property keys?

JAVASCRIPT
const a = {};
const b = { key: "b" };
const c = { key: "c" };

a[b] = 123;
a[c] = 456;

console.log(a[b]);

Output:

JAVASCRIPT
456

Why?

JavaScript object property keys are strings or symbols.

When an ordinary object is used as a property key, JavaScript converts it to a primitive property key. In this example, both objects convert to the string:

JAVASCRIPT
"[object Object]"

Therefore, the assignments effectively become:

JAVASCRIPT
a["[object Object]"] = 123;
a["[object Object]"] = 456;

The second assignment overwrites the first.

That's why the result is 456.

How do we solve this if we actually want objects as keys?

Use a Map.

JAVASCRIPT
const map = new Map();

const b = { key: "b" };
const c = { key: "c" };

map.set(b, 123);
map.set(c, 456);

console.log(map.get(b)); // 123
console.log(map.get(c)); // 456

A Map can use objects as distinct keys based on object identity.


3. JSON.stringify() and JSON.parse()

Sometimes we need to convert JavaScript objects into strings.

For example, when sending data to an API, storing data in certain formats, or transferring information between systems.

JavaScript provides two useful methods:

  • JSON.stringify() converts a JavaScript value into a JSON string.

  • JSON.parse() converts a valid JSON string back into a JavaScript value.

Example

JAVASCRIPT
const user = {
  name: "Piyush",
  age: 87
};

const strObj = JSON.stringify(user);

console.log(strObj);

Output:

JAVASCRIPT
{"name":"Piyush","age":87}

Notice that the result is a string, not an object.

We can convert it back:

JAVASCRIPT
const originalObject = JSON.parse(strObj);

console.log(originalObject);
console.log(originalObject.name);

Output:

JAVASCRIPT
{ name: "Piyush", age: 87 }
Piyush

Interview Question: JSON.stringify with a Replacer Array

Consider:

JAVASCRIPT
const settings = {
  username: "lydiahallie",
  level: 19,
  health: 90
};

const data = JSON.stringify(settings, ["level", "health"]);

console.log(data);

Output:

JAVASCRIPT
{"level":19,"health":90}

Why is username missing?

Because the second argument of JSON.stringify() is a replacer.

When an array of property names is provided, only those selected properties are included in the resulting JSON string.

Important Limitations of JSON.stringify()

JSON serialization does not preserve every JavaScript value.

For example:

JAVASCRIPT
const obj = {
  name: "Piyush",
  value: undefined,
  greet() {},
  date: new Date()
};

console.log(JSON.stringify(obj));

Some values are omitted or transformed during serialization.

  • Object properties containing undefined are omitted.

  • Function-valued properties are omitted.

  • Date objects are serialized as strings.

  • Circular references cause a TypeError.

Therefore, JSON.stringify() followed by JSON.parse() is not a universal deep-cloning solution.


4. Spread Operator and Object Manipulation

The spread operator (...) allows us to expand properties from an iterable or an object into another expression.

For objects, it is commonly used to copy or combine properties.

Question 5: What is the output of the spread operator with a string?

JAVASCRIPT
console.log([..."Lydia"]);

Output:

JAVASCRIPT
["L", "y", "d", "i", "a"]

Why?

Strings are iterable in JavaScript.

The spread operator expands the string into its individual Unicode code points.

We can also use it with arrays:

JAVASCRIPT
const numbers = [1, 2, 3];

const copy = [...numbers];

console.log(copy); // [1, 2, 3]

Question 6: Object Spread

JAVASCRIPT
const user = {
  name: "Lydia",
  age: 21
};

const admin = {
  admin: true,
  ...user
};

console.log(admin);

Output:

JAVASCRIPT
{
  admin: true,
  name: "Lydia",
  age: 21
}

The spread operator copies the enumerable own properties of user into the new object.

What happens when properties have the same name?

JAVASCRIPT
const user = {
  name: "Piyush",
  age: 24
};

const updatedUser = {
  name: "Rahul",
  ...user
};

console.log(updatedUser.name); // Piyush

The spread operation comes after name: "Rahul", so the copied name overwrites the earlier value.

Reverse the order:

JAVASCRIPT
const updatedUser = {
  ...user,
  name: "Rahul"
};

console.log(updatedUser.name); // Rahul

The last assigned property value wins.


5. Understanding this in Objects

The this keyword is one of the most confusing topics in JavaScript.

Its value depends on how a function is called.

Let's understand it through an example.

Question 7: Regular Method vs Arrow Function

JAVASCRIPT
const shape = {
  radius: 10,

  diameter() {
    return this.radius * 2;
  },

  perimeter: () => 2 * Math.PI * this.radius
};

console.log(shape.diameter());
console.log(shape.perimeter());

Output in a typical browser ES module:

JAVASCRIPT
20
NaN

Why?

The regular method diameter() receives this from the object that calls it.

Therefore:

JAVASCRIPT
this.radius

refers to:

JAVASCRIPT
shape.radius

However, the arrow function does not have its own this.

It inherits this from its surrounding lexical scope.

It does not automatically receive shape as its this value.

In an ES module, top-level this is undefined. In other environments, the result can differ, but the arrow function still does not bind this to shape.

Correct approach:

JAVASCRIPT
const shape = {
  radius: 10,

  diameter() {
    return this.radius * 2;
  },

  perimeter() {
    return 2 * Math.PI * this.radius;
  }
};

console.log(shape.diameter());  // 20
console.log(shape.perimeter()); // 62.831853...

Remember: Use regular methods when you need dynamic this based on the calling object.


6. Object Destructuring

Destructuring allows us to extract properties from objects and assign them to variables.

Instead of writing:

JAVASCRIPT
const user = {
  name: "Piyush",
  age: 24
};

const name = user.name;
const age = user.age;

We can write:

JAVASCRIPT
const {
  name,
  age
} = user;

console.log(name);
console.log(age);

Question 8: Nested Object Destructuring

Consider:

JAVASCRIPT
const user = {
  name: "Piyush",
  age: 24,

  fullName: {
    firstName: "Piyush",
    lastName: "Agarwal"
  }
};

const {
  fullName: {
    firstName
  }
} = user;

console.log(firstName);

Output:

JAVASCRIPT
Piyush

Here, we are accessing a nested property directly through destructuring.

Notice that fullName is not created as a separate variable.

Only firstName is assigned.

Renaming Variables During Destructuring

We can also rename a property while extracting it.

JAVASCRIPT
const user = {
  name: "Piyush",
  age: 24
};

const {
  name: userName
} = user;

console.log(userName); // Piyush

Here, name is the original property, while userName is the new variable.

Default Values

We can provide a default value when a property is missing or its value is undefined.

JAVASCRIPT
const user = {
  name: "Piyush"
};

const {
  name,
  age = 18
} = user;

console.log(name); // Piyush
console.log(age);  // 18

7. Rest Parameters and Object References

Question 9: Can a Rest Parameter Appear in the Middle?

Consider:

JAVASCRIPT
function getItems(fruitList, ...args, favoriteFruit) {
  return [...fruitList, ...args, favoriteFruit];
}

This function is invalid.

Why?

A rest parameter must always be the last parameter in a function definition.

Correct syntax:

JAVASCRIPT
function getItems(fruitList, favoriteFruit, ...args) {
  return [...fruitList, favoriteFruit, ...args];
}

console.log(
  getItems(["banana", "apple"], "orange", "pear", "mango")
);

Output:

JAVASCRIPT
["banana", "apple", "orange", "pear", "mango"]

Question 10: What Happens When Two Variables Reference the Same Object?

JAVASCRIPT
let c = {
  greeting: "Hey!"
};

let d;

d = c;

c.greeting = "Hello";

console.log(d.greeting);

Output:

JAVASCRIPT
Hello

Why?

Because objects are reference values.

When we write:

JAVASCRIPT
d = c;

We do not create a new object.

Both variables now refer to the same object.

The important takeaway is:

Assigning an object to another variable copies the reference, not the entire object.

Question 11: Are Two Objects with Identical Properties Equal?

JAVASCRIPT
console.log({ a: 1 } == { a: 1 });
console.log({ a: 1 } === { a: 1 });

Output:

JAVASCRIPT
false
false

Why?

Every object literal creates a new object.

Even though both objects have identical properties, they are two different objects in memory.

JavaScript compares object identity, not their property contents.

Consider:

JAVASCRIPT
const a = { name: "Piyush" };
const b = a;

console.log(a === b); // true

Here, both variables reference the same object.

Question 12: What Happens When an Object Is Stored Inside an Array?

JAVASCRIPT
let person = {
  name: "Lydia"
};

const members = [person];

person = null;

console.log(members);

Output:

JAVASCRIPT
[{ name: "Lydia" }]

Why doesn't the object disappear?

Because the array contains a reference to the original object.

When we write:

JAVASCRIPT
person = null;

We only change the value stored in the variable person.

We do not modify or delete the original object.

The members array still references that object.


8. Object Mutation and Default Parameters

Question 13: Understand Object Spread and Mutation

JAVASCRIPT
const value = {
  number: 10
};

const multiply = (x = { ...value }) => {
  console.log((x.number *= 2));
};

multiply();
multiply(value);
multiply(value);

Output:

JAVASCRIPT
20
20
40

Let's understand why.

First call:

JAVASCRIPT
multiply();

No argument is provided, so JavaScript creates a new shallow copy of value.

The copied object's number becomes 20.

The original object is still 10.

Second call:

JAVASCRIPT
multiply(value);

Now we explicitly pass the original object.

Its number changes from 10 to 20.

Third call:

JAVASCRIPT
multiply(value);

We pass the same original object again.

Its number changes from 20 to 40.

Important Concept

Default parameters are evaluated whenever a function is called without the corresponding argument, or when that argument is undefined.

Since { ...value } creates a new object, every call using the default gets a separate shallow copy.


9. JavaScript Pass-by-Value with Objects

Question 14: What Happens When an Object Is Passed to a Function?

Consider:

JAVASCRIPT
function changeAgeAndReference(person) {
  person.age = 25;

  person = {
    name: "John",
    age: 50
  };

  return person;
}

const personObj1 = {
  name: "Alex",
  age: 30
};

const personObj2 = changeAgeAndReference(personObj1);

console.log(personObj1);
console.log(personObj2);

Output:

JAVASCRIPT
// personObj1
{
  name: "Alex",
  age: 25
}

// personObj2
{
  name: "John",
  age: 50
}

This is a very important interview question.

Let's break it down.

Step 1: Passing the object

JAVASCRIPT
changeAgeAndReference(personObj1);

The function receives a copy of the object reference.

Both personObj1 and the parameter person initially refer to the same object.

Step 2: Modifying the property

JAVASCRIPT
person.age = 25;

Because both references point to the same object, the original object is modified.

Step 3: Reassigning the parameter

JAVASCRIPT
person = {
  name: "John",
  age: 50
};

Now the local parameter points to a completely new object.

This does not change what personObj1 references.

Step 4: Returning the new object

JAVASCRIPT
return person;

The new object is returned and assigned to personObj2.

Important Takeaway

JavaScript is pass-by-value.

When an object is passed to a function, the value being copied is the object reference.

This means:

  • Mutating the referenced object can affect the original object.

  • Reassigning the local parameter does not reassign the caller's variable.


10. Shallow Copy vs Deep Copy

This is one of the most important concepts when working with objects in real-world applications.

Suppose we have an object:

JAVASCRIPT
const user = {
  name: "Piyush",
  address: {
    city: "Delhi",
    country: "India"
  }
};

Now we want to create a copy of this object.

How can we do that?

Shallow Copy

A shallow copy creates a new outer object but does not recursively copy nested objects.

The nested objects are still shared references.

There are several ways to create a shallow copy.

Method 1: Object.assign()

JAVASCRIPT
const copy = Object.assign({}, user);

Method 2: Spread Operator

JAVASCRIPT
const copy = { ...user };

Both create a shallow copy.

Let's understand the problem:

JAVASCRIPT
const user = {
  name: "Piyush",
  address: {
    city: "Delhi"
  }
};

const copy = { ...user };

copy.name = "Rahul";
copy.address.city = "Mumbai";

console.log(user);

Output:

JAVASCRIPT
{
  name: "Piyush",
  address: {
    city: "Mumbai"
  }
}

Why?

The outer object was copied, so changing copy.name does not affect user.name.

However, both objects still reference the same nested address object.

Therefore, changing copy.address.city also changes user.address.city.

Deep Copy

A deep copy creates an independent copy of the object, including its nested structures.

For supported values, modern JavaScript provides:

JAVASCRIPT
const copy = structuredClone(user);

Example:

JAVASCRIPT
const user = {
  name: "Piyush",
  address: {
    city: "Delhi"
  }
};

const copy = structuredClone(user);

copy.address.city = "Mumbai";

console.log(user.address.city); // Delhi
console.log(copy.address.city); // Mumbai

The nested object is also independently copied.

JSON.parse() and JSON.stringify()

Another commonly used approach is:

JAVASCRIPT
const copy = JSON.parse(
  JSON.stringify(user)
);

This works for many simple JSON-compatible objects.

However, it has limitations:

  • Functions are not preserved.

  • undefined object properties are omitted.

  • Dates become strings.

  • Map and Set are not preserved as their original types.

  • Circular references cause an error.

  • Special numeric values such as NaN and Infinity are converted to null.

For modern applications, prefer structuredClone() when its supported data types meet your requirements.

Visualizing Shallow vs Deep Copy

Comparison Table

Feature

Shallow Copy

Deep Copy

Creates a new outer object

Yes

Yes

Copies nested objects independently

No

Yes

Nested references shared

Yes

No

Suitable for simple objects

Yes

Yes

Common methods

Spread, Object.assign

structuredClone


11. Quick Revision Cheat Sheet

Concept

Important Point

Computed Properties

Dynamically create property names

for...in

Iterates over enumerable property keys

delete

Removes configurable object properties

Duplicate Keys

Last property definition wins

Object as Key

Ordinary object keys are converted to property keys

Map

Supports objects as distinct keys

JSON.stringify()

Converts values to JSON strings

JSON.parse()

Converts JSON strings back into values

Spread Operator

Copies enumerable own properties

Destructuring

Extracts properties into variables

Object Equality

Compares object identity

Object Mutation

Changes the original referenced object

Shallow Copy

Copies the outer object, shares nested references

Deep Copy

Independently copies nested structures

30-Second Interview Revision

  • Objects are reference values in JavaScript.

  • Assigning an object to another variable copies its reference.

  • Two different object literals are not equal, even if their properties match.

  • Object keys are strings or symbols; use Map for object keys.

  • The spread operator creates a shallow copy.

  • Object.assign() also creates a shallow copy.

  • structuredClone() supports deep cloning of many built-in data types.

  • JavaScript passes object references by value.

  • Regular methods receive this based on how they are called.

  • Arrow functions inherit this lexically.

  • JSON serialization has limitations and is not a universal cloning method.

Finished this lesson?

Mark this chapter complete to update your learning streak and unlock the next lesson.