Skip to main content

Arrays and Objects

Arrays and objects are the two data structures you will use in virtually every JavaScript project. Arrays store ordered lists of values; objects store key-value pairs.

Creating Arrays

const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixed = ["hello", 42, true, null];

Access elements by index (starting at 0):

console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"
console.log(fruits.length); // 3

Essential Array Methods

Adding and Removing Elements

Ctrl+Enter
HTML
CSS
JS
Preview

Searching

Ctrl+Enter
HTML
CSS
JS
Preview

Transforming Arrays

These methods return a new array without modifying the original.

map — Transform Every Element

const prices = [10, 20, 30];
const withTax = prices.map((price) => price * 1.1);

console.log(withTax); // [11, 22, 33]

filter — Keep Elements That Pass a Test

const scores = [85, 42, 93, 67, 78];
const passing = scores.filter((score) => score >= 70);

console.log(passing); // [85, 93, 78]

reduce — Accumulate a Single Value

const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((total, n) => total + n, 0);

console.log(sum); // 15

Chaining Methods

Array methods can be chained for powerful one-liners:

Ctrl+Enter
HTML
CSS
JS
Preview

Sorting Arrays

The sort() method sorts in place and converts elements to strings by default.

Ctrl+Enter
HTML
CSS
JS
Preview

Destructuring Arrays

Pull values out of arrays into named variables:

Ctrl+Enter
HTML
CSS
JS
Preview

The Spread Operator

The spread operator ... expands an array into individual elements.

Ctrl+Enter
HTML
CSS
JS
Preview

Creating Objects

Ctrl+Enter
HTML
CSS
JS
Preview

Shorthand Properties

When the variable name matches the key name:

const name = "Alex";
const age = 28;

const person = { name, age }; // same as { name: name, age: age }

Destructuring Objects

Ctrl+Enter
HTML
CSS
JS
Preview

Iterating Over Objects

Ctrl+Enter
HTML
CSS
JS
Preview

Spreading and Merging Objects

Ctrl+Enter
HTML
CSS
JS
Preview

Later spreads overwrite earlier ones for duplicate keys.

Optional Chaining

Safely access deeply nested properties without checking each level:

Ctrl+Enter
HTML
CSS
JS
Preview

Practical Exercise

Build a student grade tracker:

Ctrl+Enter
HTML
CSS
JS
Preview

Key Takeaways

  • Use map, filter, and reduce instead of manual loops for cleaner, more readable code.
  • Destructuring lets you extract values from arrays and objects into named variables.
  • The spread operator creates shallow copies and merges arrays or objects.
  • Optional chaining (?.) prevents errors when accessing nested properties that might not exist.
  • Chain array methods together for expressive data transformations.