INF310: Modern JS, Fall 2017 > Language Features > Arrays
Arrays

Arrays are objects with their prototype set to Array.prototype.

Array literals
  const emptyArray = [];
  const numbers = ['one', 2, { three: true }];

Notice each array is a separate object

  [] === [] // false
  [1, 2, 3] === [1, 2, 3] // false
Array length

The length property contains the largest index of the array plus one.

  const arr = [];
  arr.length // 0

  arr[5] = 6;
  arr.length // 6

  arr // 5 empty slots, 6
Checking if something is an array
  const arr = [];

  // the typeof operator has no notion of arrays
  typeof arr // "object"

  // use Array.isArray instead
  Array.isArray(arr) // true
Array methods

There a lot of useful methods that arrays inherit from Array.prototype.

push

Add an element to the end of an array.

  array.push(newElement);
pop

Remove and return the last element of the array

  let lastElement = array.pop();
join

Returns a string combining all elements with the given delimiter.

  ['hello', 'crazy', 'world'].join('! ');
  // returns "hello! crazy! world"
concat

Retruns a new array containing all the given values.

  [1, 2, 3].concat([4, 5]); // returns [1, 2, 3, 4, 5]
slice

Return a copy of a sub array, starting from the given index and having the given length

  const numbers = [1, 2, 3, 4, 5];
  numbers.slice(0,2); // returns [1, 2];
splice

Modifies the given array: adding, removing or replacing elements

  const numbers = [1, 2, 3, 4, 5];
  const fourAndFive = numbers.splice(3, 2);
  // fourAndFive = [4, 5];
  // numbers = [1, 2, 3];
forEach

Execute the given function on each element of the array.

  array.forEach((el) => console.log(el));
some

Returns true if any of the elements satisfy the condition function

[1, 2, 3, 4, 5].some(number => number % 2); // returns true
every

Returns true if all the elements satisfy the predicate

[1, 2, 3, 4, 5].some(number => number % 2); // returns false
filter

Apply the given function to each element of the array. If the function returns true, the value is added to the new results array.

  const evenOnly = [1, 2, 3, 4, 5].filter(number => number % 2);
map

Returns an array of the result of applying the given function to each element of the array.

  const doubled = [1, 2, 3, 4, 5].map(number => number * 2);
  // returns [2, 4, 6, 8, 10]
reduce

Accumulate a result by applying the given function to each element.

  const summed = [1, 2, 3, 4, 5]
    .reduce((result, number) => result + number, 0); // 15
Typed arrays