Lesson 37: Mastering JavaScript Array basics with challenges!

manoj ymkmanoj ymk
5 min read

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

  1. Create an array of integers and reverse it without using .reverse().

  2. Write a function that returns the second-largest number in an array.

  3. 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 of undefined. What went wrong?

  • You're using forEach and trying to return from it, but itโ€™s not working. Why?


๐Ÿ’ผ Real-World Interview Traps & Wins

โœ… Best Practices

  • Prefer .map, .filter, .reduce over manual for loops for transformations.

  • Use Array.isArray() instead of typeof to check arrays.

  • Clone arrays using [...arr] or arr.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 use for, 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

MethodMutates?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() supports return like map โ€” it doesnโ€™t.

  • Expecting .map() or .filter() to mutate the original array โ€” they donโ€™t.

  • Confusing slice() with splice() (names are too similar!).

๐Ÿ’ก Performance Tips

  • Avoid using shift() or unshift() 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([]) and setItems(prev => [...prev, newItem]).

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk