JavaScript Array & Object Interview Questions (With Answers)
You’ve learned how arrays and objects work. Now let’s see how interviewers like to test them.
Most of these questions look simple. But they’re built around one or two small details that trip people up. So try to work out each answer yourself before reading the explanation.
1. What’s the difference between map() and forEach() in JavaScript?
Section titled “1. What’s the difference between map() and forEach() in JavaScript?”const prices = [100, 200, 300];
const withTax = prices.map((price) => price * 1.1);
const result = prices.forEach((price) => price * 1.1);
console.log(withTax); // [110, 220, 330]
console.log(result); // undefined
In the above example, you can see that:
map()runs the callback on every item and puts whatever you return into a new array. That’s whywithTaxhas the new prices.forEach()also runs the callback on every item, but it throws away whatever you return. It always returnsundefined.- Neither of them changes the original
pricesarray.
So, use map() when you want a new array back, and forEach() when you just want to do something with each item, like logging it or saving it somewhere.
2. What’s the difference between slice() and splice() in JavaScript?
Section titled “2. What’s the difference between slice() and splice() in JavaScript?”const fruits = ["apple", "banana", "mango", "grapes"];
const sliced = fruits.slice(1, 3);
console.log(sliced); // ["banana", "mango"]
console.log(fruits); // ["apple", "banana", "mango", "grapes"]
const removed = fruits.splice(1, 2);
console.log(removed); // ["banana", "mango"]
console.log(fruits); // ["apple", "grapes"]
In the above example, you can see that:
slice(1, 3)copies the items from index1up to (but not including) index3. The original array is untouched.splice(1, 2)starts at index1and removes2items from the original array. It returns the removed items.- After
splice(),fruitshas only two items left.
The names are almost the same, which is exactly why interviewers love this one. An easy way to remember it is that splice changes, slice doesn’t.
3. Why does changing a copied array change the original?
Section titled “3. Why does changing a copied array change the original?”const a = [1, 2, 3];
const b = a;
b.push(4);
console.log(a);
Answer: [1, 2, 3, 4]
Wait, what? We only pushed into b!
In the above example, you can see that:
- Arrays and objects aren’t stored inside the variable. The variable only holds a reference, which is like an address pointing to where the array lives in memory.
const b = adoesn’t create a new array. It copies the address, soaandbpoint to the same array.- So when we push
4throughb, we’re changing the one array both of them point to.
It’s like two people having the same house key. If one of them rearranges the furniture, the other one walks into a rearranged house too.
4. Why does [1, 2] === [1, 2] return false?
Section titled “4. Why does [1, 2] === [1, 2] return false?”console.log([1, 2] === [1, 2]);
console.log({ name: "Riya" } === { name: "Riya" });
const user = { name: "Riya" };
const sameUser = user;
console.log(user === sameUser);
Answer: false, false, true
In the above example, you can see that:
- When you compare arrays or objects, JavaScript doesn’t compare what’s inside them. It compares their references.
- Each
[1, 2]creates a brand-new array at a different place in memory. Same content, but different addresses, so it’sfalse. - Same thing for the two
{ name: "Riya" }objects. sameUserholds the same reference asuser, souser === sameUseristrue.
5. Why does changing a spread copy change the original object?
Section titled “5. Why does changing a spread copy change the original object?”const user = {
name: "Riya",
address: { city: "Delhi" }
};
const copy = { ...user };
copy.name = "Aman";
copy.address.city = "Mumbai";
console.log(user.name);
console.log(user.address.city);
Answer: Riya and Mumbai
Hmm, you may be wondering why name stayed the same but city changed?
In the above example, you can see that:
{ ...user }creates a shallow copy. It creates a new outer object and copies each property one level deep.nameis a string, so its value gets copied. Changingcopy.namedoesn’t touchuser.name.addressis an object, so only its reference gets copied. Bothuser.addressandcopy.addresspoint to the same inner object.- So changing
copy.address.cityalso changesuser.address.city.
To copy everything, including nested objects, use a deep copy:
const deepCopy = structuredClone(user);
deepCopy.address.city = "Mumbai";
console.log(user.address.city); // Delhi
We covered this in detail in the Arrays article under Shallow Copy vs Deep Copy.
6. Can you change a const array or object in JavaScript?
Section titled “6. Can you change a const array or object in JavaScript?”const skills = ["HTML", "CSS"];
skills.push("JavaScript");
console.log(skills); // ["HTML", "CSS", "JavaScript"]
const user = { name: "Riya" };
user.name = "Aman";
console.log(user.name); // Aman
user = { name: "Karan" }; // TypeError: Assignment to constant variable.
In the above example, you can see that:
constdoesn’t mean the value can’t change. It means the variable can’t be pointed somewhere else.- Pushing into
skillsand changinguser.namework fine, because we’re changing what’s inside the same array or object. user = { ... }tries to pointuserto a brand-new object, and that’s whatconstblocks.
If you want to actually stop an object from changing, use Object.freeze().
7. Why does sort() sort numbers in the wrong order?
Section titled “7. Why does sort() sort numbers in the wrong order?”const numbers = [10, 1, 5, 100, 25];
numbers.sort();
console.log(numbers);
Answer: [1, 10, 100, 25, 5]
Wait, what? That’s not sorted at all!
In the above example, you can see that:
- By default,
sort()converts every item to a string and sorts them alphabetically. - As strings,
"10"comes before"5"because"1"comes before"5", just like"apple"comes before"banana". - So we get the dictionary order, not the number order.
To sort numbers properly, pass a compare function:
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 10, 25, 100]
If a - b is negative, a goes first. If it’s positive, b goes first. Use b - a to sort from biggest to smallest.
8. How do you count how many times each item appears in an array?
Section titled “8. How do you count how many times each item appears in an array?”This is a very common coding question, and reduce() makes it easy.
const fruits = ["apple", "banana", "apple", "mango", "banana", "apple"];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(count); // { apple: 3, banana: 2, mango: 1 }
In the above example, you can see that:
- We start
reduce()with an empty object{}as the starting value ofacc. - For every fruit, we check whether it already exists in
acc. If it doesn’t,acc[fruit]isundefined, so(undefined || 0)gives0. - We add
1to the count and store it back. - We must
return accat the end of the callback, so the next round gets the updated object.
9. Does Object.freeze() freeze nested objects?
Section titled “9. Does Object.freeze() freeze nested objects?”const settings = Object.freeze({
theme: "dark",
font: { size: 16 }
});
settings.theme = "light";
settings.font.size = 20;
console.log(settings.theme);
console.log(settings.font.size);
Answer: dark and 20
In the above example, you can see that:
Object.freeze()stops us from changing the properties ofsettings, sothemestays"dark".- But freeze is shallow, just like the spread copy. It only freezes the first level.
fontis a nested object, and that inner object is not frozen. Sofont.sizechanges to20.
Notice that settings.theme = "light" didn’t throw an error either. It failed silently. In strict mode, it would throw a TypeError instead.
10. How do you remove duplicates from an array in JavaScript?
Section titled “10. How do you remove duplicates from an array in JavaScript?”const tags = ["js", "css", "js", "html", "css"];
const unique = [...new Set(tags)];
console.log(unique); // ["js", "css", "html"]
In the above example, you can see that:
- A
Setis a built-in collection that only keeps unique values. Any duplicates are dropped automatically. new Set(tags)creates a set with"js","css"and"html".- The spread operator
...turns the set back into a normal array.
Interviewers sometimes ask you to do it without Set. You can use filter() for that:
const unique = tags.filter((tag, index) => tags.indexOf(tag) === index);
indexOf() always returns the first position of an item. So we keep a tag only if this is the first time we’ve seen it.
🧵 Wrapping It Up
Section titled “🧵 Wrapping It Up”You practiced how to:
- Pick between
map()andforEach(), and betweenslice()andsplice() - Spot when two variables point to the same array or object
- Tell a shallow copy from a deep copy, and know what
constandObject.freeze()actually protect - Sort numbers correctly and count items with
reduce()
Most array and object questions come down to one idea. Variables hold a reference to arrays and objects, not the array or object itself.