JavaScript Course
JavaScript
/
Beginner

Arrays & Methods

Definition

An ordered, integer-indexed collection of values. JavaScript arrays can hold mixed data types and dynamically resize themselves.

Explain Like I'm New

An array is a list of items kept in a specific order, like a grocery list. Item 0 is milk, Item 1 is bread. You can easily add items to the end (`push`), remove from the end (`pop`), or loop through all of them (`forEach`).

Real World Example

Storing a list of a user's recent transactions, and using `array.reduce()` to calculate the total sum of their expenses.

Common Use Cases

  • •Storing ordered data
  • •Iterating and transforming lists of objects

Terminal Output

bash / terminal
const numbers = [1, 2, 3, 4, 5]; // Map: Returns a new array (creates [2, 4, 6, 8, 10]) const doubled = numbers.map(num => num * 2); // Filter: Returns a new array with items that pass the test const evens = numbers.filter(num => num % 2 === 0); // Reduce: Condenses the array into a single value const sum = numbers.reduce((accumulator, currentVal) => accumulator + currentVal, 0); // Splice: Mutates original array (Removes 1 item at index 2) numbers.splice(2, 1); console.log(numbers); // [1, 2, 4, 5]

Interview Questions

basic

  • What is the difference between `map` and `forEach`?

intermediate

  • What is the difference between `slice` and `splice`?

advanced

  • Why is sorting an array of numbers `[1, 10, 2].sort()` dangerous in JS?

Flash Cards

Question

map vs forEach?

Click to reveal answer
Answer

`forEach` executes a function on every item but returns `undefined` (used for side effects). `map` executes a function on every item and returns a brand NEW array with the transformed items (used to modify data without mutating the original).

Question

Why is [1, 10, 2].sort() dangerous?

Click to reveal answer
Answer

Because the default `.sort()` method converts all elements to Strings and sorts them alphabetically. Alphabetically, '10' comes before '2'. So the array becomes `[1, 10, 2]`. To fix this, you must provide a compare function: `arr.sort((a,b) => a - b)`.