Skip to content

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:

  1. map() runs the callback on every item and puts whatever you return into a new array. That’s why withTax has the new prices.
  2. forEach() also runs the callback on every item, but it throws away whatever you return. It always returns undefined.
  3. Neither of them changes the original prices array.

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:

  1. slice(1, 3) copies the items from index 1 up to (but not including) index 3. The original array is untouched.
  2. splice(1, 2) starts at index 1 and removes 2 items from the original array. It returns the removed items.
  3. After splice(), fruits has 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:

  1. 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.
  2. const b = a doesn’t create a new array. It copies the address, so a and b point to the same array.
  3. So when we push 4 through b, 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:

  1. When you compare arrays or objects, JavaScript doesn’t compare what’s inside them. It compares their references.
  2. Each [1, 2] creates a brand-new array at a different place in memory. Same content, but different addresses, so it’s false.
  3. Same thing for the two { name: "Riya" } objects.
  4. sameUser holds the same reference as user, so user === sameUser is true.

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:

  1. { ...user } creates a shallow copy. It creates a new outer object and copies each property one level deep.
  2. name is a string, so its value gets copied. Changing copy.name doesn’t touch user.name.
  3. address is an object, so only its reference gets copied. Both user.address and copy.address point to the same inner object.
  4. So changing copy.address.city also changes user.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:

  1. const doesn’t mean the value can’t change. It means the variable can’t be pointed somewhere else.
  2. Pushing into skills and changing user.name work fine, because we’re changing what’s inside the same array or object.
  3. user = { ... } tries to point user to a brand-new object, and that’s what const blocks.

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:

  1. By default, sort() converts every item to a string and sorts them alphabetically.
  2. As strings, "10" comes before "5" because "1" comes before "5", just like "apple" comes before "banana".
  3. 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:

  1. We start reduce() with an empty object {} as the starting value of acc.
  2. For every fruit, we check whether it already exists in acc. If it doesn’t, acc[fruit] is undefined, so (undefined || 0) gives 0.
  3. We add 1 to the count and store it back.
  4. We must return acc at 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:

  1. Object.freeze() stops us from changing the properties of settings, so theme stays "dark".
  2. But freeze is shallow, just like the spread copy. It only freezes the first level.
  3. font is a nested object, and that inner object is not frozen. So font.size changes to 20.

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:

  1. A Set is a built-in collection that only keeps unique values. Any duplicates are dropped automatically.
  2. new Set(tags) creates a set with "js", "css" and "html".
  3. 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.

You practiced how to:

  • Pick between map() and forEach(), and between slice() and splice()
  • Spot when two variables point to the same array or object
  • Tell a shallow copy from a deep copy, and know what const and Object.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.