JavaScript Arrays Interview Questions and Answers
Prepare for array questions about indexing, iteration, common methods, and working with ordered collections.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
- What is an Array in JavaScript?
- What are the properties of an Array in JavaScript?
- Difference between Array Literal and Array Object?
- What is the significance of index in an Array?
- Convert a sentence into an array of words.
- Difference between push and unshift, pop and shift?
- Sort a number array without changing the original array.
Theoretical JavaScript Interview Questions
An array is an ordered list of values accessed by a zero-based numeric index - arr[0] is the first element. Elements can be any type, including other arrays or objects, so you can model complex data. In JavaScript, arrays are actually objects under the hood, which explains why typeof [] returns 'object' - use Array.isArray() to properly check.
The most used property is length - it tells you the count of elements and you can even set it directly to truncate the array. Arrays are mutable, zero-indexed, and can hold any mix of types. They're technically objects with numeric keys, which means you can add non-numeric properties to them, though you almost never should.
Always use the literal syntax (const arr = [1, 2, 3]) - it's cleaner and avoids a nasty gotcha with the Array constructor. When you pass a single number to new Array(3), you get an empty array with length 3, not an array containing 3. That ambiguity catches people out; the literal syntax never has this problem.
Indexes are zero-based, so the first element is arr[0] and the last is arr[arr.length - 1] - or in modern JS, arr.at(-1) for negative indexing. You can read or write by index: arr[2] = 'new value'. Accessing an index that doesn't exist returns undefined rather than throwing, which can hide bugs if you're not careful.
push and pop work at the end of the array - push adds, pop removes. unshift and shift work at the start - unshift adds, shift removes. Push/pop are O(1) and very cheap. Unshift/shift are O(n) because every element needs to be re-indexed, so avoid them in performance-sensitive loops on large arrays.
slice is non-destructive - it returns a new array with the selected elements and leaves the original untouched. splice mutates the original array: it can remove elements, insert new ones, or do both at once. The easy way to remember: slice is safe to use anywhere; splice is a scalpel that cuts the original. If you find yourself reaching for splice, check if slice + a rebuild would be cleaner.
some() is like asking 'does any element match?' - it returns true as soon as it finds one match and stops. every() asks 'do all elements match?' - it returns false as soon as it finds one that doesn't. Both short-circuit, so they're efficient. Common use: some() to check if a user has any admin role, every() to validate that all form fields are filled.
flat() just flattens nested arrays - flat() by one level, flat(Infinity) all the way down. flatMap() is map + flat(1) in a single pass, which is useful when your map callback returns arrays and you don't want the result to be an array of arrays. A typical use case is splitting sentences into words: sentences.flatMap(s => s.split(' ')). For anything deeper than one level, stick to flat(depth) separately.
Methods such as map, filter, and forEach skip empty slots, so their callbacks are not called for holes. Iteration with for...of and spreading treats a hole as an undefined value. Prefer dense arrays when predictable iteration matters.
A shallow copy creates a new outer array but keeps the same element values. If an element is an object, the copied array and original still reference that same object, so changing a nested property is visible through both arrays. Deep copying requires an explicit strategy suited to the data.
Removing an element shifts later values left while the loop index continues forward, so the value shifted into the current position may never be checked. Build a new array with filter, iterate backwards when appropriate, or manage the index after each removal.
Set uses SameValueZero equality, which treats NaN values as equal and considers positive and negative zero equal. Objects are compared by identity rather than by their properties, so two separate objects with identical fields remain distinct.
Removing the first element shifts the remaining indexed elements, making each removal linear in the array length. Repeating it can therefore do quadratic work. For queue-like processing, use a moving start index or a queue structure designed for that access pattern.
JavaScript Practical and Coding Interview Questions
Problem: Write a function that returns the words in a sentence as an array.
function wordsFromSentence(sentence) {
return sentence.split(' ');
}
console.log(wordsFromSentence('learn JavaScript today'));Problem: Return the numbers in ascending order while leaving the input array unchanged.
function sortNumbers(values) {
return [...values].sort((a, b) => a - b);
}
const input = [10, 9, 2];
console.log(sortNumbers(input));
console.log(input);Problem: Sort the records by ascending age and use the name as a tie-breaker.
const users = [
{ name: 'Sam', age: 30 },
{ name: 'Ari', age: 24 },
{ name: 'Bea', age: 24 },
];
users.sort((a, b) => a.age - b.age || a.name.localeCompare(b.name));
console.log(users);Problem: Write a recursive function that returns the values from a nested array in their original order. Do not modify the input array.
function flattenList(values) {
const result = [];
for (const value of values) {
if (Array.isArray(value)) {
result.push(...flattenList(value));
} else {
result.push(value);
}
}
return result;
}
const route = ['north', ['east', ['south']], 'west'];
console.log(flattenList(route));
console.log(route);Problem: Return a new array containing pages of the requested size. Keep the final partial page and leave the input list unchanged.
function groupPages(items, pageSize) {
if (!Number.isInteger(pageSize) || pageSize <= 0) {
throw new RangeError('pageSize must be a positive integer');
}
const pages = [];
for (let index = 0; index < items.length; index += pageSize) {
pages.push(items.slice(index, index + pageSize));
}
return pages;
}
const checkpoints = ['Dawn Gate', 'Pine Bridge', 'River Turn', 'Lookout'];
console.log(groupPages(checkpoints, 3));
console.log(checkpoints);Problem: Return a new list with its values shifted right by the requested number of steps. Handle an empty list and step counts larger than the list length.
function rotateRight(values, steps) {
if (!Number.isInteger(steps)) throw new TypeError('steps must be an integer');
if (values.length === 0) return [];
const shift = ((steps % values.length) + values.length) % values.length;
if (shift === 0) return [...values];
return [...values.slice(-shift), ...values.slice(0, -shift)];
}
const stops = ['Pier', 'Market', 'Park', 'Museum'];
console.log(rotateRight(stops, 1));
console.log(stops);Problem: The input contains every integer from 1 through max except for one value. Find the missing number without sorting the list.
function findMissingNumber(values, max) {
const expectedTotal = max * (max + 1) / 2;
const actualTotal = values.reduce((total, value) => total + value, 0);
return expectedTotal - actualTotal;
}
console.log(findMissingNumber([1, 2, 4, 5, 6], 6));Problem: Return a new list with tasks marked `postponed` after the other tasks. Preserve the order within both groups and do not mutate the input.
function movePostponedToEnd(tasks) {
const ready = [];
const postponed = [];
for (const task of tasks) {
(task.status === 'postponed' ? postponed : ready).push(task);
}
return [...ready, ...postponed];
}
const tasks = [
{ name: 'Pack maps', status: 'ready' },
{ name: 'Check lanterns', status: 'postponed' },
{ name: 'Print route', status: 'ready' },
{ name: 'Charge radio', status: 'postponed' },
];
console.log(movePostponedToEnd(tasks));
console.log(tasks);Problem: Write an iterative binary search that returns the index of a target in an ascending number array, or -1 when the target is absent.
function binarySearch(values, target) {
let low = 0;
let high = values.length - 1;
while (low <= high) {
const middle = low + Math.floor((high - low) / 2);
if (values[middle] === target) return middle;
if (values[middle] < target) low = middle + 1;
else high = middle - 1;
}
return -1;
}
const voltages = [4, 9, 15, 22, 31, 40];
console.log(binarySearch(voltages, 22));
console.log(binarySearch(voltages, 18));Problem: Implement insertion sort without calling Array.sort(). Return a sorted copy and leave the input unchanged.
function insertionSort(values) {
const result = [...values];
for (let index = 1; index < result.length; index += 1) {
const current = result[index];
let position = index - 1;
while (position >= 0 && result[position] > current) {
result[position + 1] = result[position];
position -= 1;
}
result[position + 1] = current;
}
return result;
}
const lapTimes = [42, 17, 31, 9];
console.log(insertionSort(lapTimes));
console.log(lapTimes);Problem: Use the Fisher-Yates method to return a shuffled copy. Accept a random-number function so the example can use a repeatable result.
function shuffle(values, random = Math.random) {
const result = [...values];
for (let index = result.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(random() * (index + 1));
[result[index], result[swapIndex]] = [result[swapIndex], result[index]];
}
return result;
}
const topics = ['map', 'array', 'set', 'object'];
console.log(shuffle(topics, () => 0.5));
console.log(topics);