Objects, Arrays, and Destructuring

Aside from primitive (scalar) data types (string, number, boolean, etc), JavaScript also has objects and arrays. These are container types that contain other data.

Arrays

Arrays contain elements that are usually of the same type, but could be of mixed types.

let days_of_week = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
];

Array elements are ordered, starting from index 0.

let squares = [];
for (const i = 0; i < 10; i++) {
  squares[i] = i * i;
}

Use .length property and push method:

days_of_week.push('Eighth Day');
const new_array = days_of_week.concat('Ninth Day');

Use map and reduce functions:

const squares = nums.map(n => n*n);

Objects

A JavaScript Object is a grab-bag of properties (keys) and corresponding values.

const customer = {
  name: {
    first: "Jane",
    last: "Doe",
  },
  age: 21,
  tags: ["urban", "high value"],
  "suspected fraud": false,
};
  • Values can be of any type, including nested objects
  • Properties can be unquoted if they are regular identifiers
  • Props can be accessed with . or [] operators

Destructuring

Extract values from objects and arrays into variables:

const {name, age, ...without_name_and_age} = customer;
const [sq0, sq1, sq2, ...sq3to9] = squares;

Use spread operator to catch all values not already destructured.


References:
  1. MDN: JavaScript Arrays
  2. MDN: JavaScript Objects