Course Content
Data types and Values
0/1
Object-oriented programming in JavaScript
0/1
Error handling and debugging in JavaScript
0/1
JavaScript functions for string and array manipulation
0/1
JavaScript Libraries and Frameworks
0/1
JavaScript
About Lesson

JavaScript Arrays Tutorial

Arrays are an essential data structure in JavaScript that allow you to store and manipulate multiple values within a single variable. Arrays can hold a mix of different data types and are particularly useful for tasks involving collections of items.

Specifically: An array is an object that holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions.

Creating Arrays

You can create arrays using square brackets and separating elements with commas. We are formatting the array to look just like the objects that it is:


var arrayVariable = [
    "John",
    "Doe",
    30,
    false
];

Accessing Array Elements:
Array elements are accessed using zero-based indexing:
arrayVariable[0];       // "John"
arrayVariable[1];       // Doe
arrayVariable[2];       // 30
arrayVariable[3];       // false
arrayVariable.length;   // 4

Pictorially, here is how arrays are saved in memory:

We do not have to write arrays like objects, we conventionally write them on a straight line like the ones below:


  const numbers = [1, 2, 3, 4, 5];
  const fruits = ["apple", "banana", "orange"];
  const mixed = [1, "hello", true, null];

Accessing Array Elements

Once again, array elements are accessed using zero-based indexing:


  console.log(numbers[0]);    // 1
  console.log(fruits[1]);     // "banana"
  console.log(mixed[2]);      // true
  

Modifying Array Elements

You can modify array elements by assigning new values to specific indices:


  fruits[0] = "pear";
  console.log(fruits);         // ["pear", "banana", "orange"]
  

Array Length

The length property provides the number of elements in an array:


  console.log(numbers.length);     // 5
  

Adding Elements

You can add elements to the end of an array using the push method:


  fruits.push("grape");
  console.log(fruits);       // ["pear", "banana", "orange", "grape"]
  

Removing Elements

To remove elements from an array, you can use the pop method to remove the last element or the splice method to remove specific elements:


  fruits.pop();              // Removes "grape"
  console.log(fruits);       // ["pear", "banana", "orange"]
  
  fruits.splice(1, 1);       // Removes one element starting at index 1
  console.log(fruits);       // ["pear", "orange"]
  

Iterating through Arrays

You can use loops like for or forEach to iterate through array elements:


  for (let i = 0; i < numbers.length; i++) {
      console.log(numbers[i]);
  }
  
  fruits.forEach(function(fruit) {
      console.log(fruit);
  });
  

Array Methods

JavaScript provides a variety of useful array methods, such as map, filter, and reduce, for performing advanced operations on arrays.


  const doubledNumbers = numbers.map(function(num) {
      return num * 2;
  });
  
  const evenNumbers = numbers.filter(function(num) {
      return num % 2 === 0;
  });
  
  const sum = numbers.reduce(function(acc, num) {
      return acc + num;
  }, 0);
  

Array Destructuring

Destructuring allows you to extract array elements into individual variables:


  const [first, second, ...rest] = numbers;
  console.log(first); // 1
  console.log(second); // 2
  console.log(rest); // [3, 4, 5]
  

Some JavaScript Array Methods

# Method Description Example
1 push() / pop() Add/remove elements from the end of an array.
const numbers = [1, 2, 3];
numbers.push(4);
numbers.pop();
2 unshift() / shift() Add/remove elements from the beginning of an array.
const fruits = ['apple', 'banana'];
fruits.unshift('orange');
fruits.shift();
3 concat() Merge two or more arrays to create a new array.
const array1 = [1, 2];
const array2 = [3, 4];
const merged = array1.concat(array2);
4 join() Combine array elements into a string using a specified separator.
const fruits = ['apple', 'banana'];
const fruitString = fruits.join(', ');
5 slice() Create a shallow copy of an array by extracting elements based on start and end indices.
const numbers = [1, 2, 3, 4, 5];
const subArray = numbers.slice(1, 4);
6 splice() Add or remove elements from a specific position in an array.
const numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 1, 6, 7);
7 indexOf() / lastIndexOf() Find the index of an element (or its last occurrence) in an array.
const numbers = [1, 2, 3, 4, 3];
const index1 = numbers.indexOf(3);
const index2 = numbers.lastIndexOf(3);
8 includes() Check if an array contains a specific element.
const numbers = [1, 2, 3, 4, 5];
const hasThree = numbers.includes(3);
9 find() / findIndex() Retrieve the first element (or its index) that satisfies a condition.
const numbers = [1, 2, 3, 4, 5];
const even = numbers.find(num => num % 2 === 0);
const evenIndex = numbers.findIndex(num => num % 2 === 0);
10 filter() Create a new array containing elements that pass a test.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
11 map() Create a new array by applying a function to each element.
const numbers = [1, 2, 3];
const squaredNumbers = numbers.map(num => num * num);
12 reduce() / reduceRight() Apply a function to each element to accumulate a single value.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
13 forEach() Execute a function for each element in the array.
const fruits = ['apple', 'banana'];
fruits.forEach(fruit => console.log(fruit));
14 sort() Sort array elements based on provided function or their default string representation.
const numbers = [3, 1, 4, 2, 5];
numbers.sort();
15 reverse() Reverse the order of elements in an array.
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
16 every() / some() Check if all/some elements satisfy a condition.
const numbers = [1, 2, 3, 4, 5];
const allEven = numbers.every(num => num % 2 === 0);
const someEven = numbers.some(num => num % 2 === 0);
17 flat() / flatMap() Flatten nested arrays or map and flatten at the same time.
const nestedArray = [1, [2, 3], [4, [5]]];
const flatArray = nestedArray.flat();
const doubledArray = nestedArray.flatMap(num => num * 2);
18 isArray() Check if a given value is an array.
const numbers = [1, 2, 3];
const isArr = Array.isArray(numbers);
19 toString() / toLocaleString() Convert an array to a string representation.
const numbers = [1, 2, 3];
const numString = numbers.toString();
const localizedString = numbers.toLocaleString();
20 fill() Fill array elements with a static value from a start to an end index.
const numbers = [1, 2, 3, 4, 5];
numbers.fill(0, 2, 4);
21 copyWithin() Copy a sequence of array elements to another position.
const numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3);
22 keys() / values() / entries() Create iterators for keys, values, or key-value pairs.
const numbers = [1, 2, 3];
const keys = numbers.keys();
const values = numbers.values();
const entries = numbers.entries();
23 from() Create a new array from an iterable object or a string.
const iterable = 'hello';
const arrayFromIterable = Array.from(iterable);
24 of() Create a new array with individual elements as arguments.
const newArray = Array.of(1, 2, 3);