Arrays, Objects, Indexed, and Keyed Collections

Arrays

Javascript does not have an array data type, instead it has the Array object. That allows it to have functions like push(), and properties like length.

// Defining an array.
let myArray = ['one', 'two', 'three']

// Add to end of array.
myArray.push('four')

// forEach().
myArray.forEach((itemNum) => {
  console.log(`item ${itemNum}`)
})

// for..in.
for (itemNum in myArray) {
  console.log(`item ${itemNum}`)
}

Objects

Everything is an Object in javascript. Right?

// Create object.
let myObj = {name: 'My object'}

// Set object property.
// If you do this with an array, it will set the object property, but not add it to the index.
myObj['asdf'] = 'fdsa'

console.log(myObj)

Set (Indexed Collection)

You may be tempted to use an Object as a collection, but those can have additional properties you don't want to include in the iteration. A set is like an Array, but only allows for unique values.

Map (Keyed Collection)

A Map has key/value pairs with unique keys. This is what you want if you need to iterate over keyed properties.

Level
Topics