LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 9 of 25

Arrays Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Arrays · Study material

Arrays are ordered lists, and almost every program uses them – marks, carts, rows of a table, API results. JavaScript arrays are flexible (any types, any length, they grow on demand) and that flexibility creates the traps interviews love: new Array(3) vs Array.of(3), push returning the length, slice vs splice, sort() putting 100 before 25, fill([]) sharing one object, holes, and copies that are not really copies. This topic covers the core array operations; the next topic on Array Methods covers map, filter, reduce and friends. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

Creating arrays

Use a literal [ ] almost always. new Array(n) with a single number creates an array of length n with empty slots (holes) – not n undefined values – while Array.of(n) always creates an array of the given elements. Array.from(iterableOrArrayLike, mapFn) builds arrays from strings, Sets, Maps, NodeLists or { length: n }.

const a = [1, 2, 3];                                  // literal – the normal way
const b = new Array(3);                               // ONE number argument = length: 3 empty slots
const c = Array.of(3);                                // always the elements given: [3]
const d = Array.from({ length: 4 }, (_, i) => i * i); // build from a length and a function
const e = new Array(3).fill(0);                       // fill the slots with a value
console.log(a, b, c);
console.log(d, e);

Output

[ 1, 2, 3 ] [ <3 empty items> ] [ 3 ]
[ 0, 1, 4, 9 ] [ 0, 0, 0 ]

Adding and removing at the ends

MethodDoesReturns
push(...items)adds at the endnew length
pop()removes the last itemthe removed item (undefined if empty)
unshift(...items)adds at the startnew length
shift()removes the first itemthe removed item

shift and unshift must move every other element, so they are slower than push and pop on large arrays.

const q = ["b", "c"];
// push / unshift add at the end / start and RETURN THE NEW LENGTH
console.log(q.push("d"), q.unshift("a"), q);
// pop / shift remove from the end / start and RETURN THE REMOVED ITEM
console.log(q.pop(), q.shift(), q);

Output

3 4 [ 'a', 'b', 'c', 'd' ]
d a [ 'b', 'c' ]

slice vs splice

slice(start, end) returns a copy of a section (end excluded) and never changes the array. splice(start, deleteCount, ...items) changes the array – removing, inserting or replacing – and returns an array of the removed items. Both accept negative indexes counted from the end.

const nums = [10, 20, 30, 40, 50];
// slice(start, end): a COPY of part of the array – end is excluded, negatives count from the end
console.log(nums.slice(1, 3), nums.slice(-2), nums);
// splice(start, deleteCount, ...items): CHANGES the array and returns the removed items
const removed = nums.splice(1, 2, 99);
console.log(removed, nums);

Output

[ 20, 30 ] [ 40, 50 ] [ 10, 20, 30, 40, 50 ]
[ 20, 30 ] [ 10, 99, 40, 50 ]

Indexes, length and holes

Indexes start at 0 and the last element is at length - 1. arr[-1] is not the last element – it reads a property named "-1" – so use arr.at(-1). length is writable: shrinking it deletes elements, and writing beyond the end creates holes (empty slots).

const arr = [1, 2, 3, 4, 5];
console.log(arr.at(-1), arr[arr.length - 1], arr[-1]);   // [-1] is just a property called "-1"
arr.length = 2;                                          // shrinking length deletes elements
console.log(arr);
arr[5] = 6;                                              // writing past the end leaves holes
console.log(arr, arr.length);

Output

5 5 undefined
[ 1, 2 ]
[ 1, 2, <3 empty items>, 6 ] 6

Sorting and reversing

sort() and reverse() change the array in place and return the same array. Without a compare function, sort() converts elements to strings and compares them by UTF-16 code units – fine for plain words, wrong for numbers and mixed case. Pass (a, b) => a - b for numbers and a.localeCompare(b) for text. The sort is stable (equal items keep their order).

const n = [10, 9, 1, 100, 25];
console.log([...n].sort());                    // default: converts to strings and compares them
console.log([...n].sort((a, b) => a - b));     // numbers: negative → a first, positive → b first
const fruits = ["banana", "apple", "Cherry"];
console.log([...fruits].sort());               // upper-case letters sort before lower-case
console.log([...fruits].sort((a, b) => a.localeCompare(b)));

Output

[ 1, 10, 100, 25, 9 ]
[ 1, 9, 10, 25, 100 ]
[ 'Cherry', 'apple', 'banana' ]
[ 'apple', 'banana', 'Cherry' ]

Searching and joining

indexOf and lastIndexOf return a position or -1 and compare with ===; includes returns a boolean and, unlike indexOf, finds NaN. join(separator) builds a string (null and undefined become empty strings); String(arr) is the same as join(",").

const tags = ["js", "css", "html", "js"];
console.log(tags.indexOf("js"), tags.lastIndexOf("js"), tags.indexOf("php"), tags.includes("css"));
console.log(tags.join(" | "));
console.log(String(tags), [1, [2, [3]]].join("-"));   // nested arrays are joined with commas

Output

0 3 -1 true
js | css | html | js
js,css,html,js 1-2,3

Copies instead of changes (ES2023)

toSorted, toReversed, toSpliced and with(index, value) return a new array and leave the original untouched – ideal for React state and functional code.

// ES2023: copies instead of changing the original
const original = [3, 1, 2];
const sorted = original.toSorted();
const reversed = original.toReversed();
const replaced = original.with(0, 9);           // copy with index 0 replaced
const spliced = original.toSpliced(1, 1);       // copy with one element removed
console.log(original, sorted, reversed);
console.log(replaced, spliced);

Output

[ 3, 1, 2 ] [ 1, 2, 3 ] [ 2, 1, 3 ]
[ 9, 1, 2 ] [ 3, 2 ]

Array destructuring

Destructuring unpacks elements by position: skip items with empty commas, give defaults for missing (undefined) items, collect the rest with ... (which must be last), and swap variables without a temporary one.

const scores = [92, 85, 78, 64, 51];
const [first, second, ...others] = scores;      // by position; ...rest collects the remainder
console.log(first, second, others);

const [, , third = 0, , , sixth = "none"] = scores;   // skip with commas, defaults for missing items
console.log(third, sixth);

let a = 1, b = 2;
[a, b] = [b, a];                                // swap
console.log(a, b);

Output

92 85 [ 78, 64, 51 ]
78 none
2 1

Common mistakes

  • sort() on numbers – sorts as strings: [1, 10, 100, 25, 9].
  • copy = arr – both names share one array.
  • fill([]) or fill({}) – every slot holds the same object.
  • arr[-1] – undefined; use arr.at(-1).
  • if (arr.indexOf(x)) – index 0 is falsy; compare with !== -1 or use includes.
  • arr1 === arr2 to compare contents – compares references.
  • Using splice when you meant slice – the original array changes.

Key points to remember

  • new Array(3) has 3 holes; Array.of(3) is [3].
  • push/unshift return the new length; pop/shift return the removed item.
  • slice copies; splice mutates and returns removed items.
  • sort, reverse, splice, push, pop, shift, unshift, fill mutate; toSorted, toReversed, toSpliced, with copy.
  • Default sort compares strings; pass a comparator.
  • includes finds NaN, indexOf does not.
  • Spread/slice copy one level; structuredClone copies deeply.

Frequently asked questions

Are JavaScript arrays real arrays?

They are objects with integer-like keys and a special length property, optimised by engines into fast contiguous storage when used normally (no holes, consistent types).

How do I empty an array?

arr.length = 0 empties it in place (all references see the change); arr = [] points the variable at a new array and leaves other references untouched.

How do I check whether two arrays have the same contents?

Compare lengths and then each element (a.length === b.length && a.every((x, i) => x === b[i])). JSON.stringify works for simple data but fails for undefined, NaN and different key orders in objects.

Where can I learn more?

Read JavaScript Arrays and Sorting Arrays in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links