JavaScript: Arrays

Store ordered lists of values, transform them with methods, and iterate efficiently.

Creating arrays

// Literal
const tags = ['html', 'css', 'js'];

// From values
const numbers = Array.of(1, 2, 3);

// From iterable / array-like
const letters = Array.from('abc'); // ['a','b','c']

Common methods

const nums = [1, 2, 3];
nums.push(4);          // [1,2,3,4]
const doubled = nums.map(n => n * 2); // [2,4,6,8]
const evens = nums.filter(n => n % 2 === 0); // [2,4]

Iteration

const list = ['a','b','c'];

// Index-based
for (let i = 0; i < list.length; i++) {
  console.log(i, list[i]);
}

// Values
for (const value of list) {
  console.log(value);
}

// forEach
list.forEach((v, i) => console.log(i, v));

Immutable patterns

const a = [1, 2, 3];

// Add without mutating 'a'
const b = [...a, 4];       // [1,2,3,4]
const c = a.concat(4, 5);  // [1,2,3,4,5]

// Remove without mutating
const withoutFirst = a.slice(1); // [2,3]

Practice

  1. Create an array of 5 numbers; build a new array with each number squared.
  2. From ['css','html','js'], return only items containing j.
  3. Add an item to the end without mutating the original.

Next up

Quick Check

Which method adds an item to the end of an array?