Objects Methods Interview Questions
Lets understand Objects in Javascript and then discuss some of the Most Asked Interview Questions on it!
Objects are important data structures in JavaScript. They are versatile and widely used due to their ability to store key-value pairs. Arrays in JavaScript are also objects. Here's an overview of how objects work in JavaScript:
Creating an Object
const user = {
name: 'Sambit',
age: 24,
short: 'sam',
}
Accessing Properties
console.log(user.name) // Sambit
Modifying Properties
user.name = 'Rakeh'
console.log(user) // { name: 'Rakeh', age: 24, short: 'sam' }
Deleting Properties
delete user.age
console.log(user) // { name: 'Rakeh', short: 'sam' }
Question 1: delete
keyword in Object
const func = (function (a) {
delete a
return a
})(5)
console.log(func) // 5
Explanation: In JavaScript, the delete
keyword is used to delete properties from objects. However, when used with a variable (not a property), it doesn't have any effect. In this example, delete a;
has no effect because a
is a function parameter, not an object property. Hence, func
remains unchanged and prints 5
.
Computed Properties
let property = 'firstName'
let name = 'Sambit Kumar'
let person = {
[property]: name,
}
console.log(person) // { firstName: 'Sambit Kumar' }
Explanation: Computed property names allow you to create object properties dynamically using expressions. In this example, the property name firstName
is computed using the value of the property
variable, resulting in { firstName: 'Sambit Kumar' }
.
Looping through Object Properties
let userData = {
name: 'Sambit',
age: 24,
isTotallyCool: true,
}
for (let key in userData) {
console.log(key) // name, age, isTotallyCool
console.log(userData[key]) // Sambit, 24, true
}
Question 2: Output
const obj = { a: 'one', b: 'two', a: 'three' }
console.log(obj) // { a: 'three', b: 'two' }
Explanation: When multiple properties have the same name in an object literal, the last assignment wins. In this case, a: "three"
overwrites the previous value of a
, resulting in { a: 'three', b: 'two' }
.
Question 3: Create a function multiplyByTwo(obj)
that multiplies all numeric property values of obj
by 2.
let nums = {
a: 100,
b: 200,
title: 'My nums',
}
multiplyByTwo(nums)
function multiplyByTwo(obj) {
for (let key in obj) {
if (typeof obj[key] == 'number') {
obj[key] *= 2
}
}
}
console.log(nums) // { a: 200, b: 400, title: 'My nums' }
Explanation: The function multiplyByTwo
iterates through each property of the object nums
and multiplies its numeric values by 2. The title
property remains unchanged.
Question 4: Output (Important)
const a = {}
const b = { key: 'b' }
const c = { key: 'c' }
a[b] = 123
a[c] = 456
console.log(a[b]) // 456
Explanation: In JavaScript, object keys are converted to strings when used as property names. When b
and c
objects are used as keys in the a
object, they are converted to "[object Object]"
, so a[b]
and a[c]
both refer to the same property. Hence, the output is 456
.
Question 5: JSON.stringify()
and JSON.parse()
const userOne = {
name: 'piyush',
age: 87,
}
const strObj = JSON.stringify(userOne)
console.log(JSON.parse(strObj)) // { name: 'piyush', age: 87 }
Explanation: JSON.stringify()
converts a JavaScript object into a JSON string, while JSON.parse()
converts a JSON string back into a JavaScript object. In this example, strObj
contains the JSON string representation of userOne
, which is then parsed back into an object.
Question 6: Destructuring in Object
// Example:
const user = {
name: 'John',
age: 30,
city: 'New York',
}
// Destructuring assignment
const { name, age, city } = user
console.log(name) // John
console.log(age) // 30
console.log(city) // New York
Explanation:
Destructuring assignment allows you to extract values from objects and bind them to variables in a concise and readable way. In this example, we're destructuring the user
object into individual variables name
, age
, and city
, which directly correspond to the properties of the user
object. So, name
will hold the value "John"
, age
will hold 30
, and city
will hold "New York"
.
Shallow Copy vs. Deep Copy
In JavaScript, when dealing with complex data structures like objects and arrays, it's important to understand the concepts of shallow copy and deep copy.
Shallow Copy:
A shallow copy creates a new object or array, but it only copies the references to the nested objects or arrays. It means that if the original object contains nested objects or arrays, the shallow copy will create a new object with references to those nested objects, rather than creating new copies of them.
// Example of shallow copy with objects
const originalObject = { a: 1, b: { c: 2 } }
const shallowCopy = Object.assign({}, originalObject)
// Modifying a property of the shallow copy
shallowCopy.a = 5
console.log(originalObject.a) // 1 (unchanged)
console.log(shallowCopy.a) // 5 (modified)
// Modifying a nested property of the shallow copy
shallowCopy.b.c = 3
console.log(originalObject.b.c) // 3 (changed)
console.log(shallowCopy.b.c) // 3 (changed)
Deep Copy:
A deep copy creates a completely new object or array, including all nested objects and arrays. It means that the copied object is entirely independent of the original, and modifying the copied object will not affect the original, and vice versa.
// Example of deep copy with objects
const originalObject = { a: 1, b: { c: 2 } }
const deepCopy = JSON.parse(JSON.stringify(originalObject))
// Modifying a property of the deep copy
deepCopy.a = 5
console.log(originalObject.a) // 1 (unchanged)
console.log(deepCopy.a) // 5 (modified)
// Modifying a nested property of the deep copy
deepCopy.b.c = 3
console.log(originalObject.b.c) // 2 (unchanged)
console.log(deepCopy.b.c) // 3 (modified)
Conclusion:
- Shallow Copy: Copies only the top-level structure of the object or array, creating a new object or array with references to nested elements. Changes to nested elements in the copy will affect the original, and vice versa.
- Deep Copy: Creates a completely independent copy of the original object or array, including all nested elements. Changes to the deep copy will not affect the original, and vice versa.
When deciding between shallow copy and deep copy, it's essential to consider the structure of your data and whether you need independent copies of nested elements. Use shallow copy when you want to maintain references, and use deep copy when you need complete independence.
Cloning an Object
Question: How can you create a copy of an object in JavaScript without referencing its keys to the original object?
Explanation: Cloning an object is a common task in JavaScript, especially when you need to manipulate or modify data without affecting the original object. Here are three common methods for cloning an object along with their explanations:
- Using
Object.assign()
for Shallow Copy:
const obj = { a: 1, b: 2 }
const objClone = Object.assign({}, obj)
Explanation: Object.assign()
method creates a shallow copy of the obj
. It copies all enumerable own properties from one or more source objects to a target object. In this case, an empty object {}
serves as the target, and obj
is the source object.
- Using
JSON.parse()
andJSON.stringify()
for Deep Copy:
const obj = { a: 1, b: 2 }
const objClone = JSON.parse(JSON.stringify(obj))
Explanation: JSON.stringify()
serializes the obj
into a JSON string, and JSON.parse()
parses the JSON string back into a new object. This method creates a deep copy, as it serializes and then deserializes the entire object, including nested objects or arrays. However, be cautious when using this method with objects containing functions or non-JSON-compatible values, as they will be lost in the cloning process.
- Using Spread Syntax (
...
) for Shallow Copy:
const obj = { a: 1, b: 2 }
const objClone = { ...obj }
Explanation: Spread syntax (...
) creates a shallow copy of the obj
. It spreads the properties of obj
into a new object literal, effectively cloning the top-level properties. Just like Object.assign()
, this method does not create copies of nested objects or arrays.
Each of these methods has its use cases, and you should choose the one that best fits your specific requirements. If you need a shallow copy and want to maintain compatibility with older browsers, Object.assign()
is a good choice. If you need a deep copy and your object is JSON-serializable, JSON.parse()
and JSON.stringify()
can be used. Finally, if you prefer concise syntax and have no nested structures, spread syntax (...
) is a viable option.