JavaScript Array Interview Questions and Answers
In JavaScript, an array is an ordered collection of values where each value is stored at a numeric index.
- Indexing: Array elements are zero-based, meaning the first element is at index
0
, the second at1
, and so on. - Data Types: Arrays can store mixed data types including numbers, strings, objects, functions, or even other arrays (nested arrays).
- Flexibility: Arrays are dynamic in size, allowing you to add, remove, or update elements easily, making them one of the most commonly used data structures in JavaScript.
1. How do you declare an array?
Arrays are super useful for organizing lists, like a grocery list or a set of scores. You can declare an array using square brackets [] with items inside or by using the Array constructor, though brackets are simpler and more common.
Example:
let fruits = ['apple', 'banana', 'cherry'];
let numbers = new Array(1, 2, 3);
console.log(fruits);
console.log(numbers);
2. What are the different ways to create an array in JavaScript?
JavaScript provides different ways to create an array, but they differ in syntax, flexibility, and readability.
- Array literal (
[]
): The simplest and most common way. Example:let arr = [1, 2, 3];
. - Array constructor (
new Array()
): Creates arrays with given elements or an empty array of a specific length. Example:let arr = new Array(3); // empty with length 3
. - Array.of(): Creates an array from arguments regardless of type/number. Example:
let arr = Array.of(5); // [5]
. - Array.from(): Creates an array from iterable or array-like objects. Example:
let arr = Array.from("hello"); // ['h','e','l','l','o']
. - Spread operator (
...
): Copies or combines arrays easily. Example:let arr = [...[1,2], ...[3,4]]; // [1,2,3,4]
.
3. How do you access the elements of an array?
To get an item from an array, you use its index number inside square brackets []. Think of the array as a row of lockers, where each locker has a number starting from 0. For example, array[0] gets the first item, array[1] gets the second, and so on. If you try an index that doesnât exist, you get undefined.
Example:
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[5]);
4. How can you add elements to an array?
You can add items to an array using push() to add to the end or unshift() to add to the beginning. Imagine a line of people: push() adds someone to the back, like joining a queue, and unshift() adds someone to the front, like cutting in line. Both methods change the original array.
Example:
let fruits = ['apple', 'banana'];
fruits.push('cherry');
console.log(fruits);
fruits.unshift('mango');
console.log(fruits);
5. How can you remove elements from an array?
You can remove items using pop() to take off the last item or shift() to remove the first one. Think of an array as a stack of plates: pop() takes the top plate (last item), and shift() takes the bottom one (first item). Both methods modify the array and return the removed item.
Example:
let fruits = ['apple', 'banana', 'cherry'];
fruits.pop();
console.log(fruits);
fruits.shift();
console.log(fruits);
6. What is the length property of an array?
The length property tells you how many items are in an array, like counting how many things are in a basket. Itâs a number that automatically updates when you add or remove items. If the array is empty, the length is 0. You can also use it to check the size or even shorten the array by setting it.
Example:
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.length);
fruits.push('mango');
console.log(fruits.length);
fruits.length = 2;
console.log(fruits);
7. How do you check if a variable is an array?
Use Array.isArray() to confirm if something is an array. It returns true if itâs an array and false if itâs something else, like a string or number. This is helpful to avoid errors when youâre expecting an array but might get another type.
Example:
let fruits = ['apple', 'banana'];
let text = 'apple';
console.log(Array.isArray(fruits));
console.log(Array.isArray(text));
8. How do you iterate over an array?
Iterating means going through each item in an array, like checking every item on a shopping list. A for loop is a common way to do this, using the index to access each element. You start at index 0 and go until the arrayâs length, making sure you visit every item.
Example:
let fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
9. How do you use the forEach method?
The forEach method is a simpler way to loop through an array. It runs a function for each item, giving you the item, its index, and the whole array. Itâs like asking a helper to process each item in a list one by one. It doesnât create a new array or change the original unless you modify it inside the function.
Example:
let fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(`Fruit ${index + 1}: ${fruit}`);
});
10. What is the difference between for...of and for...in loops in arrays?
The for...of loop gives you the actual items in an array, like picking each fruit from a basket. The for...in loop gives you the indices (positions), like getting the numbers of the basketâs slots. For arrays, for...of is usually better because you want the items, while for...in is more for objects with named properties.
Example:
let fruits = ['apple', 'banana', 'cherry'];
for (let fruit of fruits) {
console.log(fruit);
}
for (let index in fruits) {
console.log(index);
}
11. How do you concatenate two arrays?
To combine two arrays, use the concat() method or the spread operator (...). Itâs like merging two lists into one big list. Both methods create a new array without changing the original ones, so you get a fresh combined list.
Example:
let fruits = ['apple', 'banana'];
let moreFruits = ['cherry', 'mango'];
let allFruits1 = fruits.concat(moreFruits); // Using concat
let allFruits2 = [...fruits, ...moreFruits]; // Using spread
console.log(allFruits1);
12. How does find()
differ from filter()
?
JavaScript provides array methods like find() and filter(), but they differ in purpose and return values.
- find(): Returns the first element in the array that matches the given condition (or
undefined
if none match). It stops searching once a match is found. - filter(): Returns a new array containing all elements that match the given condition. If no matches are found, it returns an empty array.
13. Explain the map method and provide an example.
The map method creates a new array by applying a function to every item in the original array. Itâs like taking each item, transforming it (e.g., doubling a number or capitalizing a word), and putting the result in a new list. The original array stays unchanged, and the new array has the same number of items.
Example:
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]
console.log(numbers); // Output: [1, 2, 3] (original unchanged)
14. How does the filter method work?
The filter method creates a new array with only the items that pass a test you define in a function. The function returns true to keep an item or false to skip it. For example, you can pick only numbers greater than 3. Itâs like sorting through a pile to keep only what you want, without touching the original pile.
Example:
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
console.log(numbers); // Output: [1, 2, 3, 4, 5]
15. Describe the reduce method with an example.
The reduce method takes an array and combines all its items into a single value using a function. The function uses an âaccumulatorâ (like a running total) and the current item to build the result. Itâs great for summing numbers, joining strings, or calculating something from all items. You can set a starting value for the accumulator.
Example:
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // Output: 10 (1 + 2 + 3 + 4)
16. What is the purpose of the find method?
The find method searches an array and returns the first item that passes a test (returns true in a function). If no item passes, it returns undefined. Itâs like looking through a list to find the first thing that matches your criteria, such as the first number over 3.
Example:
let numbers = [1, 2, 3, 4, 5];
let found = numbers.find(num => num > 3);
console.log(found); // Output: 4 (first number > 3)
17. How do you use the some method?
The some method checks if at least one item in an array passes a test (returns true in a function). It returns true if any item passes and false if none do. Itâs like asking, âIs there at least one thing in this list that fits my rule?â without checking the rest once one is found.
Example:
let numbers = [1, 2, 3, 4, 5];
let hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // Output: true (2 is even)
18. Explain the every method with an example.
The every method checks if all items in an array pass a test (return true in a function). It returns true only if every item passes; if even one fails, it returns false. Itâs like making sure everything in a list meets a standard, such as all numbers being positive.
Example:
let numbers = [1, 2, 3, 4, 5];
let allPositive = numbers.every(num => num > 0);
console.log(allPositive); // Output: true
let allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // Output: false (not all are even)
19. What does the includes method do?
The includes method checks if an array has a specific item and returns true if it does, false if it doesnât. You can also tell it where to start looking with a second argument. Itâs like searching a list to see if something specific is there.
Example:
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.includes('banana')); // Output: true
console.log(fruits.includes('mango')); // Output: false
20. How do you use the indexOf method?
The indexOf method finds the first position (index) of an item in an array. If the item isnât there, it returns -1. You can also set a starting index to skip earlier parts. Itâs like finding where a specific book is on a shelf.
Example:
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.indexOf('banana')); // Output: 1
console.log(fruits.indexOf('mango')); // Output: -1
21. What is the slice method used for?
The slice method copies a part of an array into a new array, from a start index to an end index (not including the end). Itâs like cutting out a piece of a cake without changing the original cake. It doesnât modify the original array.
Example:
let fruits = ['apple', 'banana', 'cherry', 'mango'];
let someFruits = fruits.slice(1, 3);
console.log(someFruits); // Output: ['banana', 'cherry']
console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'mango']
22. Explain the splice method with an example.
The splice method changes an array by removing, replacing, or adding items at a specific index. You specify where to start, how many items to remove, and what (if anything) to add. Itâs like editing a list by taking out or adding items in the middle, and it changes the original array.
Example:
let fruits = ['apple', 'banana', 'cherry'];
fruits.splice(1, 1, 'mango', 'grape'); // Remove 1 item at index 1, add 'mango' and 'grape'
console.log(fruits); // Output: ['apple', 'mango', 'grape', 'cherry']
23. How do you use the join method?
The join method turns an array into a string, combining all items with a separator (like a comma or space). Itâs like gluing all the items together into one line of text, useful for creating sentences or lists.
Example:
let fruits = ['apple', 'banana', 'cherry'];
let fruitString = fruits.join(', ');
console.log(fruitString); // Output: 'apple, banana, cherry'
24. What is array destructuring and how does it work?
Array destructuring lets you pull out items from an array and assign them to variables in one line. Itâs like unpacking a box of items and giving each a name. You use square brackets on the left side of an assignment, and you can even set default values if an item is missing.
Example:
let fruits = ['apple', 'banana', 'cherry'];
let [first, second] = fruits;
console.log(first, second); // Output: 'apple', 'banana'
let [a, b, c, d = 'default'] = fruits;
console.log(d); // Output: 'default' (no fourth item)
25. How do you copy an array?
To copy an array, use the spread operator (...) or Array.from. Both create a new array with the same items, like photocopying a list. This is a âshallowâ copy, meaning it copies the items but not any objects inside them.
Example:
let fruits = ['apple', 'banana', 'cherry'];
let copy1 = [...fruits]; // Spread operator
let copy2 = Array.from(fruits); // Array.from
console.log(copy1); // Output: ['apple', 'banana', 'cherry']
console.log(copy2); // Output: ['apple', 'banana', 'cherry']
26. What are array-like objects and how do you convert them to arrays?
Array-like objects have a length property and numbered items (like 0, 1, etc.) but lack array methods like push. Examples include the arguments object in functions or lists from web pages (NodeList). Convert them to arrays using Array.from or the spread operator (...) to use array methods.
Example:
function example() {
let args = Array.from(arguments); // Convert arguments to array
console.log(args); // Output: [1, 2, 3]
}
example(1, 2, 3);
let nodeList = document.querySelectorAll('div');
let divArray = [...nodeList]; // Convert NodeList to array
27. Explain the flat method.
The flat method takes an array with nested arrays (lists inside lists) and creates a new array with all items flattened into one level. By default, it flattens one level, but you can specify a depth or use Infinity to flatten all levels. Itâs like unpacking all boxes inside a big box into one flat pile.
Example:
let nested = [1, [2, 3], [4, [5]]];
let flat1 = nested.flat(); // One level
console.log(flat1); // Output: [1, 2, 3, 4, [5]]
let flat2 = nested.flat(Infinity); // All levels
console.log(flat2); // Output: [1, 2, 3, 4, 5]
28. How does the flatMap method work?
The flatMap method combines map and flat into one step. It runs a function on each item (like map), which can return an array, and then flattens the result one level. Itâs like transforming each item into a list and then squashing those lists into one array.
Example:
let numbers = [1, 2, 3];
let result = numbers.flatMap(num => [num, num * 2]);
console.log(result); // Output: [1, 2, 2, 4, 3, 6]
29. What is the Array.from method and how is it used?
The Array.from method creates a new array from something that looks like an array or can be looped over, like a string or a set. Itâs like turning a collection of items into a proper array so you can use array methods. You can also add a function to transform each item.
Example:
let str = 'hello';
let strArray = Array.from(str);
console.log(strArray); // Output: ['h', 'e', 'l', 'l', 'o']
let set = new Set([1, 2, 3]);
let setArray = Array.from(set, num => num * 2);
console.log(setArray); // Output: [2, 4, 6]
30. Explain the fill method with an example.
The fill method changes all items in an array (or a specific range) to a single value, like setting every slot to 0. It modifies the original array. You can specify a start and end index to fill only part of it. Itâs like painting every item in a list the same color.
Example:
let numbers = [10, 2, 30, 4];
numbers.sort(); // Wrong for numbers
console.log(numbers); // Output: [10, 2, 30, 4]
numbers.sort((a, b) => a - b); // Correct for numbers
console.log(numbers); // Output: [2, 4, 10, 30]
31. What does the sort method do and how can you customize it?
The sort method arranges an arrayâs items in order, changing the original array. By default, it treats items as strings, which can mess up numbers (e.g., 10 comes before 2). To sort numbers or customize the order, use a compare function that returns a negative, zero, or positive number to decide the order. Itâs like organizing a bookshelf by title or size.
Example:
let numbers = [10, 2, 30, 4];
numbers.sort(); // Wrong for numbers
console.log(numbers); // Output: [10, 2, 30, 4]
numbers.sort((a, b) => a - b); // Correct for numbers
console.log(numbers); // Output: [2, 4, 10, 30]
32. What is the reverse method and how is it used?
The reverse method flips the order of an arrayâs items, so the first becomes the last and vice versa. It changes the original array. Itâs like turning a stack upside down, useful for reversing lists like scores or names.
Example:
let fruits = ['apple', 'banana', 'cherry'];
fruits.reverse();
console.log(fruits); // Output: ['cherry', 'banana', 'apple']
33. How do you flatten a multi-dimensional array?
JavaScript provides different ways to flatten a multi-dimensional array, but they differ in simplicity, depth handling, and browser support.
- Using
flat()
: The easiest way.array.flat(depth)
flattens nested arrays up to the given depth. For fully flattening, usearray.flat(Infinity)
. - Using
reduce()
+concat()
: Combines all elements into a single array recursively. Useful when more control is needed. - Using recursion: Manually loops through elements and flattens arrays of any depth. Works in older environments without
flat()
.
34. How do you merge two arrays and remove duplicates?
To combine two arrays and remove duplicates, use a Set with the spread operator (...). A Set automatically removes duplicates, and the spread operator turns it back into an array. Itâs like merging two lists and keeping only one copy of each item.
Example:
let array1 = [1, 2, 3];
let array2 = [2, 3, 4];
let mergedArray = [...new Set([...array1, ...array2])];
console.log(mergedArray); // Output: [1, 2, 3, 4]
35. Explain the concept of array buffer and typed arrays in JavaScript.
An ArrayBuffer is a chunk of memory for storing raw binary data, like a blank notebook. Typed arrays, like Uint8Array, are ways to view and work with that data, specifying how to interpret it (e.g., as 8-bit numbers). Theyâre used for low-level tasks, like handling files or graphics, where you need precise control over data.
Example:
let buffer = new ArrayBuffer(16); // 16 bytes of memory
let view = new Uint8Array(buffer); // View as 8-bit numbers
view[0] = 255; // Set first byte
console.log(view[0]); // Output: 255
console.log(view.length); // Output: 16
36. How do you sort an array of objects by a property value?
To sort an array of objects, use the sort method with a compare function that looks at a specific property, like age or name. The function compares two objects and decides their order. Itâs like sorting a list of people by their age or name.
Example:
let users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Peter', age: 35 }
];
users.sort((a, b) => a.age - b.age);
console.log(users);
// Output: [{ name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Peter', age: 35 }]
37. What is the difference between deep copy and shallow copy of an array?
A shallow copy copies the array but not objects inside it, so changes to those objects affect both arrays. A deep copy copies everything, including nested objects, so the new array is completely independent. Think of shallow as copying a list of references and deep as copying the actual items. Use JSON.parse(JSON.stringify()) for a simple deep copy, but it has limitations with complex objects.
Example:
let original = [{ a: 1 }, { b: 2 }];
let shallowCopy = [...original];
let deepCopy = JSON.parse(JSON.stringify(original));
original[0].a = 10;
console.log(shallowCopy[0].a); // Output: 10 (affected)
console.log(deepCopy[0].a); // Output: 1 (not affected)
38. How do you remove falsy values from an array?
Falsy values are things like false, 0, '', null, undefined, or NaN. Use filter with Boolean as the function to keep only truthy values (ones that arenât falsy). Itâs like cleaning a list to keep only valid items.
Example:
let mixedArray = [0, 1, false, 2, '', 3, null, 'a', undefined];
let truthyArray = mixedArray.filter(Boolean);
console.log(truthyArray); // Output: [1, 2, 3, 'a']
39. How can you find the intersection of two arrays?
The intersection is the items common to both arrays. Use filter with includes to keep only items that appear in both arrays. Itâs like finding the overlap between two lists of names.
Example:
let array1 = [1, 2, 3, 4];
let array2 = [3, 4, 5, 6];
let intersection = array1.filter(value => array2.includes(value));
console.log(intersection); // Output: [3, 4]
40. What are sparse arrays and how do they differ from dense arrays?
Sparse arrays have gaps (missing or undefined items) at some indices, like a bookshelf with empty spots. Dense arrays have items at every index, like a fully stocked shelf. Sparse arrays use less memory for gaps but can be slower for some operations since JavaScript needs to handle the missing spots.
Example:
let denseArray = [1, 2, 3];
let sparseArray = [1, , 3]; // Missing index 1
console.log(denseArray.length); // Output: 3
console.log(sparseArray.length); // Output: 3
console.log(sparseArray[1]); // Output: undefined
41. How do you remove duplicates from an array?
To remove duplicates, use a Set, which only stores unique values, and spread it back into an array. Itâs like taking a list with repeated names and keeping only one of each.
Example:
let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
42. Explain the copyWithin method with an example.
The copyWithin method copies part of an array to another spot in the same array, overwriting whatâs there. You specify where to copy to, where to copy from, and optionally where to stop copying. Itâs like moving a section of a list to another position, changing the original list.
Example:
let arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3); // Copy from index 3 to index 0
console.log(arr); // Output: [4, 5, 3, 4, 5]
43. How can you convert an array to a string?
Use toString() or join to turn an array into a string. toString() combines items with commas, while join lets you choose a separator, like spaces or dashes. Itâs like turning a list into a sentence.
Example:
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.toString()); // Output: 'apple,banana,cherry'
console.log(fruits.join(', ')); // Output: 'apple, banana, cherry'
44. When are findLast
/ findLastIndex
better than find
/ indexOf
?
JavaScript provides four methods to search arrays: find, indexOf, findLast, and findLastIndex, but they differ in direction and flexibility of the search.
- find: Returns the first element in the array that satisfies a testing function, searching from start to end.
- indexOf: Returns the index of the first exact match of a value, also searching from start to end.
- findLast: Returns the first element that satisfies a testing function, but searches from end to start.
- findLastIndex: Returns the index of the first element that satisfies a testing function, but searches from end to start.
45. What are array methods keys(), values(), and entries()?
The keys(), values(), and entries() methods give you iterators to loop through an arrayâs indices, values, or both. keys() returns indices (like 0, 1, 2), values() returns items, and entries() returns pairs of index and item. Use them with a spread operator to get arrays or in loops. Itâs like getting a list of slot numbers, items, or both from a storage rack.
Example:
let arr = ['a', 'b', 'c'];
console.log([...arr.keys()]); // Output: [0, 1, 2]
console.log([...arr.values()]); // Output: ['a', 'b', 'c']
console.log([...arr.entries()]); // Output: [[0, 'a'], [1, 'b'], [2, 'c']]
48. What is the Array.of method?
The Array.of method creates a new array from any number of arguments, no matter their type. Unlike the Array constructor, it treats numbers as items, not a length. Itâs like making a list from whatever items you give it, whether numbers, strings, or mixed.
Example:
let arr1 = Array.of(1, 2, 3);
let arr2 = Array.of('a', 'b', 'c');
console.log(arr1); // Output: [1, 2, 3]
console.log(arr2); // Output: ['a', 'b', 'c']
49. How do you fill an array with a specific value?
The fill method sets all items in an array (or a specific range) to one value, like filling a list with zeros. It changes the original array. You can specify start and end indices to fill only part of it, like painting a section of a wall.
Example:
let arr = new Array(5).fill(0); // Create array with five 0s
console.log(arr); // Output: [0, 0, 0, 0, 0]
let numbers = [1, 2, 3, 4];
numbers.fill(9, 1, 3); // Fill from index 1 to 2 with 9
console.log(numbers); // Output: [1, 9, 9, 4]
50. How can you sort an array of objects by multiple properties?
To sort objects by multiple properties, use the sort method with a compare function that checks one property first (e.g., name) and, if theyâre equal, checks another (e.g., age). Itâs like sorting a class list by last name, then by first name for matching last names.
Example:
let users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'John', age: 20 }
];
users.sort((a, b) => {
if (a.name === b.name) return a.age - b.age;
return a.name.localeCompare(b.name);
});
console.log(users);
// Output: [{ name: 'Jane', age: 25 }, { name: 'John', age: 20 }, { name: 'John', age: 30 }]
51. How do you implement a binary search in an array?
A binary search finds an item in a sorted array by repeatedly splitting the search range in half. If the middle item is the target, youâre done; if itâs too low, search the right half; if too high, search the left half. Itâs like guessing a number by narrowing down the range with each try, but the array must be sorted first.
Example:
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
let sortedArray = [1, 2, 3, 4, 5, 6, 7];
console.log(binarySearch(sortedArray, 5)); // Output: 4
52. What is the findIndex method and how is it used?
The findIndex method returns the index of the first item in an array that passes a test (returns true in a function). If no item passes, it returns -1. Itâs like finding the position of the first item in a list that matches your rule, such as the first number over 3.
Example:
let numbers = [1, 2, 3, 4, 5];
let index = numbers.findIndex(num => num > 3);
console.log(index); // Output: 3 (index of 4)