JavaScript Object Interview Questions
An object in JavaScript is a data structure used to store related data collections. It stores data as key-value pairs, where each key is a unique identifier for the associated value. Objects are dynamic, meaning properties can be added, modified, or deleted at runtime.
- Keys: Always strings or symbols that act as identifiers.
- Values: Can be of any data type, including numbers, strings, arrays, functions, or even other objects.
- Usage: Commonly used to represent real-world entities (like a user with name, age, and email) and to group related data together.
1. How do you add dynamic key values in an object?
You can add a key-value pair to an object dynamically using bracket notation (object[key] = value) or dot notation if the key is known. Bracket notation is especially useful when the key is stored in a variable, like when you donât know the key name until runtime. Think of it like labeling a box with a name you decide on the spot and putting something inside it.
Example:
let dynamicKey = 'age';
let dynamicValue = 25;
let user = {};
user[dynamicKey] = dynamicValue; // Adds key 'age' with value 25
console.log(user);
Explanation: The empty object user is created. The variable dynamicKey holds the string 'age', and dynamicValue holds 25. Using bracket notation (user[dynamicKey]), the key 'age' is added to user with the value 25. This is dynamic because the key comes from a variable, not a fixed name.
2. What will be the output of an object with duplicate keys?
const obj = {
a: 1,
b: 2,
a: 3
};
console.log(obj);
Output:
{ a: 3, b: 2 }
Explanation: In JavaScript, an object canât have duplicate keys. If you try to add the same key multiple times, the last value overwrites the earlier ones. Itâs like writing a name on a label and then sticking a new value over it. Here, the key a is defined twice: first with 1, then with 3. The second value (3) replaces the first, so the final object has a: 3 and b: 2.
3. Create a function multiplyByTwo(obj) that multiplies all numeric values in an object by 2?
let nums = {
a: 100,
b: 200,
title: 'My nums'
};
function multiplyByTwo(obj) {
for (let key in obj) {
if (typeof obj[key] === 'number') {
obj[key] *= 2; // Multiply numeric values by 2
}
}
}
multiplyByTwo(nums);
console.log(nums);
Output:
{ a: 200, b: 400, title: 'My nums' }
Explanation: The multiplyByTwo function loops through each key in the object using a for...in loop, like checking every label on a box. It uses typeof to check if the value is a number. If it is, the value is multiplied by 2 (e.g., 100 * 2 = 200). Non-numeric values, like the string 'My nums', are left unchanged. The object is modified directly because objects are passed by reference, so nums ends up with a: 200, b: 400, and title: 'My nums'.
4. What will be the output when using objects as keys in another object?
const obj1 = {};
const obj2 = { key: 'b' };
const obj3 = { key: 'c' };
obj1[obj2] = 123;
obj1[obj3] = 234;
console.log(obj1[obj2]);
Output:
234
Explanation: When you use an object as a key in another object, JavaScript converts it to a string using its toString() method. For most objects, this returns '[object Object]'. So, both obj2 and obj3 become the key '[object Object]' in obj1. The second assignment (obj1[obj3] = 234) overwrites the first (obj1[obj2] = 123) because they use the same key. Itâs like labeling two boxes with the same name; the latest one wins. Thus, obj1[obj2] returns 234, and obj1 is { '[object Object]': 234 }.
5. What are JSON.stringify() and JSON.parse(), and where do we use them?
JSON.stringify() turns a JavaScript object into a JSON string, like packing an object into a text format for sending or storing. JSON.parse() converts a JSON string back into a JavaScript object, like unpacking the text to use it again. Theyâre used when sending data to a server (e.g., in APIs), saving data in local storage, or reading data from files, because JSON is a universal text format that works across systems.
Example:
const settings = { theme: 'dark', notifications: true };
localStorage.setItem('userSettings', JSON.stringify(settings)); // Save as string
const storedSettings = JSON.parse(localStorage.getItem('userSettings')); // Retrieve as object
console.log(storedSettings);
Explanation: The settings object is converted to a JSON string with JSON.stringify() and stored in localStorage. Later, JSON.parse() converts the string back into an object for use. This is like saving a file as text and then reopening it to get the original data.
6. Whatâs the difference between objects created with {}
vs new Object()
?
JavaScript provides two ways to create objects: using {} (object literal) and new Object(), but they differ in readability and usage style.
- {} (object literal): Creates an object directly in a shorter and cleaner way. Itâs the most common and preferred method because itâs concise and easier to read.
- new Object(): Creates an object using the built-in
Object
constructor. Itâs longer, less commonly used, and generally avoided unless you specifically need to use the constructor form.
7. How do Object.keys()
, Object.values()
, and Object.entries()
differ?
JavaScript provides three useful methods to work with objects: Object.keys(), Object.values(), and Object.entries(), but they differ in what they return.
- Object.keys(obj): Returns an array of the objectâs own enumerable property keys (property names).
- Object.values(obj): Returns an array of the objectâs own enumerable property values.
- Object.entries(obj): Returns an array of keyâvalue pairs (
[key, value]
) from the objectâs own enumerable properties.
8. What will be the output when spreading a string into an array?
console.log([...'GFG']);
Output:
['G', 'F', 'G']
Explanation: The spread operator (...) breaks an iterable, like a string, into individual items. A string like 'GFG' is iterable, so ...'GFG' splits it into its characters: 'G', 'F', 'G'. These are placed into a new array using square brackets [...]. Itâs like taking a word and putting each letter into a separate box in a list, resulting in ['G', 'F', 'G'].
9. What will be the output when using the spread operator with an object?
const obj1 = { name: 'GFG', age: 14 };
const obj2 = { alpha: 'rule', ...obj1 };
console.log(obj2);
Output:
{ alpha: 'rule', name: 'GFG', age: 14 }
Explanation: The spread operator (...) copies all properties from obj1 into obj2. Itâs like taking all the labels and items from one box and adding them to another. Here, obj2 starts with alpha: 'rule', then adds name: 'GFG' and age: 14 from obj1. The result is a new object combining all properties. If there were duplicate keys, the later value would overwrite the earlier one.
10. What will be the output when using JSON.stringify() with a replacer array?
const obj = {
name: 'GFG',
level: 4,
company: true
};
const res = JSON.stringify(obj, ['name', 'level']);
console.log(res);
Output:
{"name":"GFG","level":4}
Explanation: JSON.stringify() converts an object to a JSON string. The second argument, an array ['name', 'level'], acts as a filter, telling it to include only the listed properties. Itâs like packing only specific items from a box into a package. Here, only name and level are included, so company is left out. The output is a JSON string with just those properties: {"name":"GFG","level":4}.
11. What will be the output of methods using this in regular vs. arrow functions?
const operation = {
value: 20,
multi() {
return this.value * 10;
},
divide: () => this.value / 10
};
console.log(operation.multi());
console.log(operation.divide());
Output:
200
NaN
Explanation: The multi method is a regular function, so this refers to the operation object, accessing value: 20 and returning 20 * 10 = 200. The divide method is an arrow function, which doesnât have its own this. Instead, it uses the this from the surrounding scope (often the global object, like window in browsers), where value is undefined. So, undefined / 10 results in NaN. Itâs like multi knowing itâs part of the object, but divide looking somewhere else and finding nothing.
12. What is object destructuring?
Object destructuring is a shorthand syntax to unpack properties from an object into distinct variables. You use curly braces {}
with property names to directly assign values from the object. You use curly braces {}
with property names to directly assign values from the object
const user = { name: "Alice", age: 25 };
const { name, age } = user;
console.log(name); // "Alice"
console.log(age); // 25
13. Why does this function result in a syntax error?
function Items(list, ...param, list2) {
return [list, ...param, list2];
}
Items(['a', 'b'], 'c', 'd');
Explanation: This code causes a syntax error because the rest parameter (...param) must be the last parameter in a function definition. Here, list2 comes after ...param, which is invalid. The rest parameter is like a bucket that collects all remaining arguments, so nothing can come after it. To fix it, you could remove list2 or restructure the function.
Corrected Example:
function Items(list, ...param) {
return [list, ...param];
}
console.log(Items(['a', 'b'], 'c', 'd')); // Output: [['a', 'b'], 'c', 'd']
14. What will be the output when assigning an object to another variable?
let obj1 = { name: 'GFG' };
let obj2 = obj1;
obj1.name = 'GeeksForGeeks';
console.log(obj2.name);
Output:
GeeksForGeeks
Explanation: Assigning obj1 to obj2 doesnât create a new object; both variables point to the same object in memory. Itâs like two people holding the same boxâchanging the contents affects both. When obj1.name changes to 'GeeksForGeeks', obj2.name sees the same change because they refer to the same object.
15. What will be the output when comparing two objects?
console.log({ name: 'GFG' } == { name: 'GFG' });
console.log({ name: 'GFG' } === { name: 'GFG' });
Output:
false
false
Explanation: In JavaScript, comparing objects with == or === checks their memory references, not their contents. Each { name: 'GFG' } creates a new object in a different memory location, even if they look identical. Itâs like comparing two identical boxes stored in different placesâtheyâre not the same box. Both comparisons return false because the objects are different references.
16. What will be the output when setting an object to null after storing it in an array?
let obj1 = { name: 'GFG' };
let obj2 = [obj1];
obj1 = null;
console.log(obj2);
Output:
[{ name: 'GFG' }]
Explanation: When obj1 is added to the array obj2, the array stores a reference to the object { name: 'GFG' }. Setting obj1 to null only changes the obj1 variable, not the object it pointed to. The array obj2 still holds a reference to the original object, so it remains unchanged. Itâs like putting a box in a bag and then throwing away the boxâs labelâthe box is still in the bag.
17. What will be the output when using a default parameter with the spread operator?
let obj = { num: 2 };
const fun = (x = { ...obj }) => {
console.log((x.num /= 2));
};
fun();
fun();
fun(obj);
fun(obj);
Output:
1
1
1
0.5
Explanation: The function fun has a default parameter x that creates a new object by spreading obj ({ ...obj }). For the first two calls (fun()), a new copy of { num: 2 } is created each time, and x.num /= 2 divides num by 2, logging 1. These donât affect obj. For the third call (fun(obj)), obj is passed directly, so x refers to obj, and num becomes 1. The fourth call (fun(obj)) uses the same obj, now { num: 1 }, so num becomes 0.5. Itâs like making copies of a box for the first two calls but editing the original box for the last two.
18. What is a shallow copy and deep copy?
A shallow copy creates a new object but copies references to nested objects, so changes to nested objects affect both the original and the copy. Itâs like copying a list of addresses but not the houses themselves. A deep copy creates a completely independent object, duplicating all nested objects, so changes to the copy donât affect the original. Itâs like building a new house for each address.
19. When would you use Object.freeze
, Object.seal
, or Object.preventExtensions?
JavaScript provides three methods to control object mutability: Object.freeze, Object.seal, and Object.preventExtensions, but they differ in how strictly they restrict modifications.
- Object.freeze: Makes an object completely immutableâno adding, deleting, or changing properties. Use when you want a read-only object that must stay fixed.
- Object.seal: Prevents adding or removing properties but allows updating existing property values. Use when the object structure should stay the same but values may change.
- Object.preventExtensions: Prevents adding new properties but allows deleting and updating existing ones. Use when you want to stop growth of an object but still allow modifications to whatâs already there.
20. How do you merge two objects in JavaScript?
JavaScript provides multiple ways to merge two objects, but the most common are using the spread operator and Object.assign().
- Spread Operator (
...
): Creates a shallow copy and merges properties into a new object. If keys overlap, the later objectâs values overwrite the earlier ones. - Object.assign(): Copies properties from one or more source objects into a target object. Like spread, overlapping keys get overwritten by the last source.
21. How do you deep copy or clone an object?
To deep copy an object, use JSON.stringify() to turn it into a string and JSON.parse() to turn it back into a new object. This creates a fully independent copy, including nested objects. Itâs like photocopying a whole book, including every page, to make a separate version. Note: This method doesnât work with functions, undefined, or circular references.
Example:
const original = { name: 'John', address: { city: 'New York', zip: 10001 } };
const cloned = JSON.parse(JSON.stringify(original));
cloned.address.city = 'Los Angeles';
console.log(original.address.city);
console.log(cloned.address.city);
Explanation: The original object has a nested address object. JSON.stringify() converts it to a string, and JSON.parse() creates a new, independent object. Changing cloned.address.city doesnât affect original, proving itâs a deep copy.