π¨ JavaScript Β· Topic 8 of 20
Arrays β JavaScript Questions with Answers
30 practice questions on Arrays, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.
5 easy Β· 16 medium Β· 9 hard Β· Part of JavaScript: The language of the web - basics to advanced, 20 topics.
Easy questions (5)
Q1. easy
Which line creates an array of three numbers?
- A const nums = [1, 2, 3];
- B const nums = {1, 2, 3};
- C const nums = (1, 2, 3);
- D const nums = array(1, 2, 3);
Answer: A β const nums = [1, 2, 3];
Square brackets create an array literal. Curly braces make an object, and parentheses are just grouping.
ArraysLiterals
Q2. easy
What is the output?
const a = ["x", "y", "z"];
console.log(a[1]);
- A "y"
- B "x"
- C "z"
- D 1
Answer: A β "y"
Array indexes start at 0, so a[0] is "x" and a[1] is "y".
Indexing
Q3. easy
What does arr.length give?
const a = [10, 20, 30];
console.log(a.length); // 3
console.log(a[a.length - 1]); // 30 - last item
- A The number of elements
- B The last index
- C The array as a string
- D The memory size
Answer: A β The number of elements
length counts elements, so the LAST index is always length - 1. Reading arr[arr.length] gives undefined.
lengthIndexing
Q5. easy
Which method adds an element to the END of an array?
const a = [1, 2];
a.push(3); // [1, 2, 3]
a.unshift(0); // [0, 1, 2, 3]
- A push()
- B append()
- C add()
- D unshift()
Answer: A β push()
push() appends and returns the new length. unshift() adds to the START, pop() removes from the end, shift() removes from the start.
pushunshift
Q10. easy
How do you check whether an array contains a value?
const a = [10, 20];
console.log(a.includes(20)); // true
console.log(20 in a); // false! (checks index 20)
- A arr.includes(value)
- B arr.contains(value)
- C value in arr
- D arr.has(value)
Answer: A β arr.includes(value)
includes() returns true/false. Note 'in' checks INDEXES for arrays, not values - a common mistake. indexOf(value) !== -1 is the older approach.
includesindexOf
Medium questions (16)
Q4. medium
What does arr.at(-1) return?
const a = [1, 2, 3];
console.log(a.at(-1)); // 3
console.log(a[-1]); // undefined
- A The LAST element - at() supports negative indexes
- B The first element
- C undefined
- D An error
Answer: A β The LAST element - at() supports negative indexes
at() (ES2022) accepts negative indexes counting from the end, unlike bracket notation where arr[-1] is undefined.
at()Negative index
Q6. medium
What does pop() return and do?
const a = [1, 2, 3];
const last = a.pop();
console.log(last, a); // 3 [1, 2]
- A Removes the LAST element and returns it
- B Removes the first element
- C Returns the last element without removing
- D Empties the array
Answer: A β Removes the LAST element and returns it
pop() shortens the array by one and hands back the removed value. shift() does the same at the start (but is slower, since all indexes shift).
popshift
Q8. medium
How do you REMOVE 2 elements starting at index 1?
const a = [1, 2, 3, 4];
a.splice(1, 2);
console.log(a); // [1, 4]
- A arr.splice(1, 2)
- B arr.slice(1, 2)
- C arr.remove(1, 2)
- D delete arr[1]
Answer: A β arr.splice(1, 2)
splice(startIndex, howMany) removes in place. delete arr[1] leaves an empty hole and does NOT change length - almost never what you want.
splicedelete
Q9. medium
How do you INSERT "x" at index 1 without deleting anything?
const a = [1, 3];
a.splice(1, 0, 2);
console.log(a); // [1, 2, 3]
- A arr.splice(1, 0, "x") - delete count of 0
- B arr.insert(1, "x")
- C arr.push(1, "x")
- D arr[1] = "x" // this overwrites
Answer: A β arr.splice(1, 0, "x") - delete count of 0
Passing 0 as the delete count makes splice a pure insertion. Option D would REPLACE the existing element instead.
spliceInsertion
Q11. medium
What does arr.indexOf("z") return when "z" is absent?
- A -1
- B undefined
- C null
- D 0
Answer: A β -1
indexOf returns the first matching index, or -1 for 'not found'. It uses strict equality, so indexOf("5") will not find the number 5.
indexOfSearch
Q14. medium
How do you make a (shallow) copy of an array?
- A [...arr], arr.slice(), or Array.from(arr)
- B arr.copy()
- C const b = arr;
- D arr.clone()
Answer: A β [...arr], arr.slice(), or Array.from(arr)
All three create a new array with the same elements. Note it is SHALLOW: nested objects are still shared. Use structuredClone(arr) for a deep copy.
SpreadsliceCopying
Q15. medium
How do you merge two arrays into a new one?
const a = [1, 2], b = [3];
console.log([...a, ...b]); // [1, 2, 3]
console.log(a.concat(b)); // [1, 2, 3]
a.push(b); // [1, 2, [3]] - nested!
- A [...a, ...b] or a.concat(b)
- B a + b
- C a.merge(b)
- D a.push(b)
Answer: A β [...a, ...b] or a.concat(b)
Spread and concat both return a NEW array. a + b would coerce both to strings; a.push(b) would nest b as a single element.
concatSpread
Q16. medium
What does arr.join("-") do?
console.log(["a","b","c"].join("-")); // "a-b-c"
console.log([1,2,3].join("")); // "123"
- A Returns a STRING with all elements separated by "-"
- B Joins two arrays
- C Removes duplicates
- D Sorts the array
Answer: A β Returns a STRING with all elements separated by "-"
join converts an array to a string using the given separator (default is a comma). The reverse is string.split(separator).
joinsplit
Q19. medium
How do you remove duplicates from an array?
const a = [1, 2, 2, 3];
console.log([...new Set(a)]); // [1, 2, 3]
- A [...new Set(arr)]
- B arr.unique()
- C arr.distinct()
- D arr.dedupe()
Answer: A β [...new Set(arr)]
A Set stores only unique values; spreading it back gives an array. Order is preserved.
SetDeduplication
Q20. medium
How do you check whether a value is an array?
console.log(typeof []); // "object"
console.log(Array.isArray([])); // true
- A Array.isArray(value)
- B typeof value === "array"
- C value instanceof Object
- D value.isArray()
Answer: A β Array.isArray(value)
typeof gives "object" for arrays, so it cannot distinguish them. Array.isArray() is the reliable test.
Array.isArraytypeof
Q23. medium
How do you create an array of 5 zeros?
console.log(new Array(3).fill(0)); // [0, 0, 0]
console.log(Array.from({length: 3}, (_, i) => i)); // [0, 1, 2]
- A new Array(5).fill(0)
- B new Array(0, 5)
- C Array(5)
- D [0 * 5]
Answer: A β new Array(5).fill(0)
Array(5) makes a sparse array of 5 holes; fill(0) turns them into real zeros. Array.from({length: 5}, () => 0) also works.
fillArray.from
Q25. medium
How do you access an element in a 2D array (array of arrays)?
const m = [[1, 2], [3, 4]];
console.log(m[1][0]); // 3
- A matrix[row][col]
- B matrix[row, col]
- C matrix(row)(col)
- D matrix.get(row, col)
Answer: A β matrix[row][col]
Chain the brackets: the first picks the inner array, the second picks an element from it.
2D arraysNested
Q26. medium
What does arr.flat() do?
console.log([1, [2, 3], [4]].flat()); // [1, 2, 3, 4]
console.log([1, [2, [3]]].flat(Infinity)); // [1, 2, 3]
- A Flattens nested arrays one level deep (flat(Infinity) flattens completely)
- B Sorts the array
- C Removes duplicates
- D Converts to a string
Answer: A β Flattens nested arrays one level deep (flat(Infinity) flattens completely)
flat() unwraps nested arrays. flatMap() maps then flattens one level - handy for producing multiple items per input.
flatflatMap
Q27. medium
How do you convert a string to an array of characters?
console.log([..."abc"]); // ["a","b","c"]
console.log("abc".split("")); // ["a","b","c"]
- A [...str] or str.split("")
- B str.toArray()
- C Array(str)
- D str.chars()
Answer: A β [...str] or str.split("")
Both work; spread handles emoji/surrogate pairs better than split(""). Array.from(str) is equivalent to spread.
Spreadsplit
Q28. medium
What does destructuring do here?
const [first, second] = [10, 20, 30];
const [a, , c] = [1, 2, 3]; // a=1, c=3 (skipped 2)
const [head, ...tail] = [1, 2, 3]; // head=1, tail=[2,3]
- A Assigns first = 10 and second = 20, ignoring the rest
- B Creates one array
- C SyntaxError
- D first becomes the whole array
Answer: A β Assigns first = 10 and second = 20, ignoring the rest
Array destructuring unpacks by POSITION. Use rest to capture the remainder, and commas to skip elements.
DestructuringRest
Q29. medium
How do you swap two variables using destructuring?
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
- A [a, b] = [b, a];
- B a, b = b, a;
- C swap(a, b);
- D a = b; b = a;
Answer: A β [a, b] = [b, a];
The right side builds an array with the current values, then destructuring assigns them back swapped - no temporary variable needed.
DestructuringSwapping
Hard questions (9)
Q7. hard
What is the difference between slice() and splice()?
const a = [1, 2, 3, 4];
console.log(a.slice(1, 3)); // [2, 3] - a unchanged
a.splice(1, 2); // a is now [1, 4]
- A slice() returns a COPY and leaves the original alone; splice() MUTATES the array (removing/inserting)
- B They are identical
- C splice() returns a copy
- D slice() deletes elements
Answer: A β slice() returns a COPY and leaves the original alone; splice() MUTATES the array (removing/inserting)
slice(start, end) extracts a section without side effects. splice(start, deleteCount, ...items) changes the array in place and returns the removed elements.
- Remember: sPlice mutates (P for 'permanent').
slicespliceMutation
Q12. hard
What is the output?
console.log([1, 2] === [1, 2]);
const a = [1, 2];
const b = a;
console.log(a === b); // true - same object
- A false - each literal creates a NEW object, and objects compare by reference
- B true
- C undefined
- D Error
Answer: A β false - each literal creates a NEW object, and objects compare by reference
Arrays are objects; === asks 'is it the same object in memory?'. Two separate arrays are never ===. Compare contents with JSON.stringify(a) === JSON.stringify(b) or an every() check.
Reference equalityComparison
Q13. hard
What is the output?
const a = [1, 2];
const b = a;
b.push(3);
console.log(a);
const b = [...a]; // independent copy
b.push(3);
console.log(a); // [1, 2] - unaffected
- A [1, 2, 3] - b is another name for the same array
- B [1, 2]
- C [3]
- D Error
Answer: A β [1, 2, 3] - b is another name for the same array
Assignment copies the REFERENCE, not the array. To copy: [...a], a.slice() or Array.from(a).
ReferencesCopying
Q17. hard
Why does [10, 9, 100].sort() give [10, 100, 9]?
console.log([10,9,100].sort((a,b) => a-b)); // [9, 10, 100]
- A The default sort converts elements to STRINGS and compares alphabetically
- B sort() is random
- C It sorts descending
- D It is a browser bug
Answer: A β The default sort converts elements to STRINGS and compares alphabetically
"10" < "100" < "9" alphabetically. For numbers pass a comparator: sort((a, b) => a - b) for ascending, (a, b) => b - a for descending.
- One of the most common real-world JavaScript bugs.
sortComparator
Q18. hard
Does sort() mutate the original array?
const a = [3, 1, 2];
const sorted = [...a].sort(); // keep a intact
// or: a.toSorted()
- A Yes - sort() and reverse() change the array in place (use toSorted() to avoid this)
- B No, it returns a copy
- C Only for numbers
- D Only in strict mode
Answer: A β Yes - sort() and reverse() change the array in place (use toSorted() to avoid this)
sort(), reverse(), splice(), push(), pop(), shift(), unshift() and fill() all MUTATE. ES2023 added non-mutating twins: toSorted(), toReversed(), toSpliced(), with().
MutationtoSorted
Q21. hard
What is the output?
const a = [1, 2, 3];
a.length = 1;
console.log(a);
- A [1] - assigning to length TRUNCATES the array
- B [1, 2, 3]
- C Error
- D [1, undefined, undefined]
Answer: A β [1] - assigning to length TRUNCATES the array
length is writable: shrinking it deletes trailing elements; growing it creates empty slots. arr.length = 0 is a quick way to empty an array in place.
lengthTruncation
Q22. hard
What is a 'sparse array'?
const a = [1, , 3];
- A An array with HOLES - missing slots that many methods skip
- B A very large array
- C An array of nulls
- D A syntax error
Answer: A β An array with HOLES - missing slots that many methods skip
Holes are not the same as undefined values: forEach and map skip them, while for...of visits them as undefined. Sparse arrays arise from delete arr[i] or setting a large length - best avoided.
Sparse arraysHoles
Q24. hard
What is the output?
const grid = new Array(2).fill([]);
grid[0].push("x");
console.log(grid[1]);
const grid = Array.from({length: 2}, () => []);
grid[0].push("x");
console.log(grid[1]); // [] - independent
- A ["x"] - fill puts the SAME array reference in every slot
- B []
- C undefined
- D Error
Answer: A β ["x"] - fill puts the SAME array reference in every slot
fill([]) evaluates the literal once and shares that one array across all slots. Build independent rows with Array.from({length: 2}, () => []).
fillReferences2D arrays
Q30. hard
What is the output?
console.log([1, 2, 3] + [4, 5]);
- A "1,2,34,5" - both arrays become strings and concatenate
- B [1,2,3,4,5]
- C [5, 7, 3]
- D Error
Answer: A β "1,2,34,5" - both arrays become strings and concatenate
+ has no array meaning, so each array is converted via join(",") - giving "1,2,3" + "4,5". To merge properly use concat or spread.
Coercionconcat