Lesson 37: Mastering JavaScript Array basics with challenges!

What is an Array in JavaScript?
An array is a special variable used to store ordered collections of items. These items can be of any type โ numbers, strings, objects, even other arrays. Arrays are zero-indexed, meaning the first item is at index 0
.
let fruits = ['apple', 'banana', 'cherry'];
JavaScript arrays are dynamic, meaning you can grow or shrink them on the fly. Internally, they behave like objects with numbered keys, and are equipped with many built-in methods for manipulating data.
๐น 2. Fill Any Gaps
Hereโs what many tutorials gloss over or oversimplify:
โ Arrays are objects under the hood:
typeof [] // 'object'
โ Sparse arrays:
let arr = []; arr[5] = 'x'; // creates empty slots (not `undefined`) in-between
โ
length
is not read-only:arr.length = 2; // truncates the array
โ Arrays can have non-integer properties (but that's bad practice):
arr['foo'] = 'bar'; // not counted in `length`
Also often overlooked: performance pitfalls when misusing array methods (forEach
vs map
, or accidentally using delete
instead of splice
).
Deep Technical Clarifications:
Why
arr.at
(-1)
?
arr[arr.length - 1]
is verbose.at(-1)
simplifies reverse indexing and improves readability.Why is
for..in
bad on arrays?
It iterates over all enumerable properties, including non-numeric keys. Itโs meant for objects.Whatโs the actual type of an array?
Arrays are objects with integer-based keys and some special behaviors.Sparse arrays & performance traps:
let a = []; a[1000] = 'x'; // creates a sparse array (slow & inefficient)
Modifying
length
is powerful but risky:arr.length = 0; // Clears the entire array
๐น 3. Challenge Me Deeply
๐ข Basic
Create an array of integers and reverse it without using
.reverse()
.Write a function that returns the second-largest number in an array.
Remove all falsy values (
false
,0
,''
,null
,undefined
,NaN
) from an array.
๐ก Intermediate
4. Flatten a 2D array into a 1D array without using .flat()
.
5. Rotate an array n
times to the right.
6. Find the frequency of each element in an array.
7. Implement a custom .map()
method called myMap()
.
๐ด Advanced
8. Find the longest increasing subsequence in an array.
9. Write a function to deeply compare two arrays (including nested arrays).
10. Create a custom Array.prototype.chunk(size)
that breaks an array into subarrays of size n
.
๐ฏ Bonus Brain-Twister
11. Given an array of integers, rearrange them to form the largest possible number (e.g., [10, 2] โ "210"
).
๐น 4. Interview-Ready Questions
๐ง Concept-Based
How are arrays different from objects in JavaScript?
Explain the difference between
.slice()
and.splice()
.What is the time complexity of
.push()
and.shift()
?
๐ฏ Scenario-Based
Your app needs to keep a history of user actions. How would you use arrays to store and limit this history?
You have to transform an array of user objects into a lookup table by user ID. How would you do this?
๐ Debugging-Style
You run
.map()
on an array, but the result is full ofundefined
. What went wrong?You're using
forEach
and trying toreturn
from it, but itโs not working. Why?
๐ผ Real-World Interview Traps & Wins
โ Best Practices
Prefer
.map
,.filter
,.reduce
over manualfor
loops for transformations.Use
Array.isArray()
instead oftypeof
to check arrays.Clone arrays using
[...arr]
orarr.slice()
to avoid side effects.
๐ซ Red Flags
Using
delete
on array indices โ it leaves holes:delete arr[1]; // bad, use arr.splice(1,1)
Misusing
for-in
loops with arrays (should usefor
,for-of
, or.forEach
).
๐น 5. Real-World Usage
โ Arrays are everywhere:
Data manipulation in dashboards (transforming API results).
Storing DOM elements after
document.querySelectorAll()
.Maintaining undo-redo stacks in editors.
Search filters for e-commerce platforms.
Buffers and Streams in Node.js โ often use typed arrays.
๐น 6. Remember Like a Pro
๐ง Mnemonics
MAP-FS:
Map
,Array
,Push
,Filter
,Splice
โ common verbs of Array land.Think of arrays as "ordered buckets" โ each bucket can hold anything and the position matters.
๐ Cheatsheet
Method | Mutates? | Description |
push/pop | โ | Add/remove from end |
shift/unshift | โ | Add/remove from start |
splice | โ | Add/remove anywhere |
slice | โ | Copy part of array |
map | โ | Transform each item |
filter | โ | Keep only what passes condition |
reduce | โ | Accumulate into a single value |
๐น 7. Apply It in a Fun Way
๐ฎ Mini Game: Build a memory card game โ use an array to store card states, shuffle cards, track matches, and manage score.
๐ฒ Dice Simulator: Roll a virtual die n
times and store each roll in an array. Visualize frequency.
๐งโโ๏ธ Wizard Spell Queue: Each spell cast gets pushed into an array. Display them with delays and clear with shift
.
๐ธ Bonus: Insights, Mistakes & Power Tips
โ ๏ธ Common Mistakes
Thinking
.forEach()
supportsreturn
likemap
โ it doesnโt.Expecting
.map()
or.filter()
to mutate the original array โ they donโt.Confusing
slice()
withsplice()
(names are too similar!).
๐ก Performance Tips
Avoid using
shift()
orunshift()
on large arrays โ they reindex everything.Preallocate arrays if you know the size (
new Array(n)
), especially in heavy loops.
๐ Open-Source Patterns
Lodash uses array methods under the hood in many utilities.
React often manages state with arrays:
useState([])
andsetItems(prev => [...prev, newItem])
.
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
