πŸŽ“ Velnov

🟨 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.

Key concepts in this topic

ArraysLiteralsIndexinglengthat()Negative indexpushunshiftpopshiftslicespliceMutationdeleteInsertionincludesindexOfSearchReference equalityComparisonReferencesCopyingSpreadconcat

Jump to: Easy Β· Medium Β· Hard

Easy questions (5)

Q1. easy

Which line creates an array of three numbers?

  1. A const nums = [1, 2, 3];
  2. B const nums = {1, 2, 3};
  3. C const nums = (1, 2, 3);
  4. 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]);

  1. A "y"
  2. B "x"
  3. C "z"
  4. 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
  1. A The number of elements
  2. B The last index
  3. C The array as a string
  4. 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]
  1. A push()
  2. B append()
  3. C add()
  4. 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)
  1. A arr.includes(value)
  2. B arr.contains(value)
  3. C value in arr
  4. 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
  1. A The LAST element - at() supports negative indexes
  2. B The first element
  3. C undefined
  4. 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]
  1. A Removes the LAST element and returns it
  2. B Removes the first element
  3. C Returns the last element without removing
  4. 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]
  1. A arr.splice(1, 2)
  2. B arr.slice(1, 2)
  3. C arr.remove(1, 2)
  4. 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]
  1. A arr.splice(1, 0, "x") - delete count of 0
  2. B arr.insert(1, "x")
  3. C arr.push(1, "x")
  4. 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?

  1. A -1
  2. B undefined
  3. C null
  4. 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?

  1. A [...arr], arr.slice(), or Array.from(arr)
  2. B arr.copy()
  3. C const b = arr;
  4. 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!
  1. A [...a, ...b] or a.concat(b)
  2. B a + b
  3. C a.merge(b)
  4. 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"
  1. A Returns a STRING with all elements separated by "-"
  2. B Joins two arrays
  3. C Removes duplicates
  4. 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]
  1. A [...new Set(arr)]
  2. B arr.unique()
  3. C arr.distinct()
  4. 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
  1. A Array.isArray(value)
  2. B typeof value === "array"
  3. C value instanceof Object
  4. 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]
  1. A new Array(5).fill(0)
  2. B new Array(0, 5)
  3. C Array(5)
  4. 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
  1. A matrix[row][col]
  2. B matrix[row, col]
  3. C matrix(row)(col)
  4. 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]
  1. A Flattens nested arrays one level deep (flat(Infinity) flattens completely)
  2. B Sorts the array
  3. C Removes duplicates
  4. 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"]
  1. A [...str] or str.split("")
  2. B str.toArray()
  3. C Array(str)
  4. 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]
  1. A Assigns first = 10 and second = 20, ignoring the rest
  2. B Creates one array
  3. C SyntaxError
  4. 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
  1. A [a, b] = [b, a];
  2. B a, b = b, a;
  3. C swap(a, b);
  4. 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]
  1. A slice() returns a COPY and leaves the original alone; splice() MUTATES the array (removing/inserting)
  2. B They are identical
  3. C splice() returns a copy
  4. 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
  1. A false - each literal creates a NEW object, and objects compare by reference
  2. B true
  3. C undefined
  4. 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
  1. A [1, 2, 3] - b is another name for the same array
  2. B [1, 2]
  3. C [3]
  4. 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]
  1. A The default sort converts elements to STRINGS and compares alphabetically
  2. B sort() is random
  3. C It sorts descending
  4. 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()
  1. A Yes - sort() and reverse() change the array in place (use toSorted() to avoid this)
  2. B No, it returns a copy
  3. C Only for numbers
  4. 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);

  1. A [1] - assigning to length TRUNCATES the array
  2. B [1, 2, 3]
  3. C Error
  4. 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];

  1. A An array with HOLES - missing slots that many methods skip
  2. B A very large array
  3. C An array of nulls
  4. 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
  1. A ["x"] - fill puts the SAME array reference in every slot
  2. B []
  3. C undefined
  4. 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]);

  1. A "1,2,34,5" - both arrays become strings and concatenate
  2. B [1,2,3,4,5]
  3. C [5, 7, 3]
  4. 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

Practice β€œArrays” as a quiz