An ARRAY is a collection of elements identified by an index (it is often called a list in other programming languages). Arrays can be thought of as a sequential block of data in memory; in other words, order matters!

In compiled languages like Java and C++ you need to declare the length and data type of an array in advance; with JavaScript we do not. The language takes care of resizing and data types for us.

Arrays are great for data you need to iterate over in sequence but not for searching since its BigO is O(n). If you have a coding challenge to “find” or “search” for data probably don’t want an array.

Basic Array

Here is a basic array we are setting to the variable days.

let days = ['Monday', 'Tuesday', 'Wednesday']
console.log(days); // ['Monday', 'Tuesday', 'Wednesday']

We can access the index since our array is sequential.

days[0]; // 'Monday'
days[1]; // 'Tuesday'

There is a lengthy list of built-in methods we can use on our array.

Here are just a few:

days.length; // 3
days.includes('Friday'); // false
days.includes('Tuesday'); // true
days.push('Thursday'); // add to end of array
console.log(days); // ['Monday', 'Tuesday', 'Wednesday', 'Thursday']
days.pop(); // remove last item in array
console.log(days); // ['Monday', 'Tuesday', 'Wednesday']

Build an Array From Scratch

You might be asked in an interview to build an array. Here is one approach using classes.

// Operations: add, remove, search, getAtIndex, length, print
class MyArray {
  constructor() {
    this.array = [];
  }

  add(data) {
    this.array.push(data);
  }

  remove(data) {
    this.array = this.array.filter(current => current !== data);
  }

  search(data) {
    if (this.array.includes(data)) {
      return this.array.indexOf(data);
    }
    return null;
  }

  getAtIndex(index) {
    returnthis.array[index];
  }

  length() {
    return this.array.length;
  }

  print() {
    console.log(this.array.join(' '));
  }
}

const arr = new MyArray();
arr.add(1);
arr.add(2);
arr.add(5);
arr.print(); // 1 2 5
arr.length(); // 3
arr.search(5); // 2
arr.remove(2);
arr.print(); // 1 5




Want to improve your JavaScript? I have a list of recommended JavaScript books.