Basic

Arrays and Objects

Organize data with arrays and objects, the two most common containers.

What you will see

Ada 3

About 3 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

Store ordered items in an array and labelled data in an object, then pull values apart with destructuring and spread. Inspect each change as you go.

1

Add an item to the end of an array and read the first slot and the new length. Array indexing starts at zero, so the first element is at index 0.

const fruits = ["apple", "banana", "cherry"]; fruits.push("date"); console.log(fruits[0]); console.log(fruits.length);

Before you run it, say out loud what it will print. Then open the answer.

What it prints
apple 4
`push` adds to the end and `pop` removes from it; `unshift`/`shift` work at the front. Indexing starts at 0, so fruits[fruits.length] is undefined.
2

Read object properties with dot and bracket syntax, add a new key, and delete one. Bracket notation is required when the key is stored in a variable.

const person = { name: "Ada", age: 30 }; person.city = "London"; delete person.age; console.log(person.name, person.city);

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Ada London
Access properties with dot or bracket notation. Use brackets for dynamic keys that are not valid identifiers or stored in a variable.
3

Destructure a property into a variable, then build a new object with spread while adding a field. Count the keys to confirm the copy landed.

const person = { name: "Ada", age: 30 }; const { name } = person; const rest = { ...person, city: "London" }; console.log(name); console.log(Object.keys(rest).length);

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Ada 3
Destructuring unpacks values into variables; spread copies enumerable properties into a new container. Spread is shallow, so nested objects stay shared.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

Items are stored in ordered arrays or keyed objects and retrieved by position or key.
1 Create array/object -> empty container
↓
2 Push/set -> store new entry
↓
3 Index or key lookup -> fetch value
↓
4 Iterate -> read or transform each entry
Why this works
Array iteration methods

Arrays have a rich set of iteration methods:

const nums = [1, 2, 3];
nums.forEach(n => console.log(n));   // run side effects
nums.map(n => n * 2);                // transform
nums.filter(n => n > 1);             // subset
nums.find(n => n > 1);               // first match
nums.some(n => n > 2);               // any match
nums.every(n => n > 0);              // all match

forEach returns nothing and is for side effects; map/filter/reduce return new arrays/values and compose well.

Objects under the hood

An object is a map of string keys to values. Modern engines optimize objects used as data containers. Use arrays for ordered, numeric-indexed collections and objects for keyed lookup:

const map = new Map();
map.set(1, "one");     // keys can be anything
map.get(1);             // 'one'

const set = new Set([1, 1, 2]); // unique only: Set {1, 2}

Map and Set (ES2015) give unique collections and any-key maps, which are faster for large dynamic data than plain objects.

Examples

Array basics

Ordered collections

const fruits = ["apple", "banana", "cherry"];
fruits.push("date");        // add to end
fruits.pop();               // remove from end
console.log(fruits[0]);     // apple
console.log(fruits.length); // 3

Arrays are ordered lists. push/pop add/remove at the end; unshift/shift work at the front. Indexing starts at 0.

Object properties

Key/value storage

const person = { name: "Ada", age: 30 };
console.log(person.name);       // Ada
console.log(person["age"]);     // 30
person.city = "London";         // add key
delete person.age;              // remove key

Objects store labelled data. Access with dot syntax or bracket notation. Use bracket notation when the key is dynamic or not a valid identifier.

Destructuring and spread

Pulling values apart

const person = { name: "Ada", age: 30 };
const { name, age } = person;   // extract properties
const rest = { ...person, city: "London" }; // copy + add
const [first, ...others] = [1, 2, 3];   // destructure array

Destructuring unpacks values into variables. The spread ... copies enumerable properties into a new object or array without sharing a reference.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Functions
Previous Lesson
Functions
Next Lesson
Asynchronous JavaScript
Asynchronous JavaScript →