Get In Touch
admin@victoriaweb.me
Back

Arrays in JavaScript

An array is a variable that contains a list of data, where each element has its own index and can be accessed through that index. Indexing of array elements starts at zero. An array can contain various types of data: other arrays (multidimensional arrays), objects, numbers, strings.

Arrays allow storing and processing large lists of data, for example, a list of products in an online store or storing a user’s profile

Example of an array with different data types:

const mixedArray = [
  42,                          // Number
  "Hello",                     // String
  true,                        // Boolean
  null,                        // null
  undefined,                   // undefined
  { name: "John", age: 30 },   // Object
  [1, 2, 3],                   // Array
  function() { return "Hi"; }, // Function
  new Date(),                  // Date
  /pattern/,                   // RegExp
  Symbol('id'),                // Symbol
  123n,                        // BigInt
  NaN,                         // NaN
  Infinity                     // Infinity
];

console.log(mixedArray);
// 1. Array of strings (names):
const names = ["Olga", "Andriy", "Maria", "Taras", "Irina"];

// 2. Array of numbers:
const ages = [18, 25, 30, 42, 57];

// 3. Mixed array (various data types):
const mixed = [ true, "JS", 2023, null, { skill: "coding" } ];

// 4. Array of objects:
const products = [
  { id: 1, name: "Laptop", price: 20000 },
  { id: 2, name: "Smartphone", price: 10000 },
  { id: 3, name: "Headphones", price: 800 }
];

// 5. Two-dimensional (nested) array:
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

Examples of string arrays, number arrays, mixed arrays, object arrays, nested (two-dimensional) arrays

Values in an array can be changed: removed, replaced, added. Changes can be made to the original array using special methods available in JS for working with arrays. These methods are divided into two groups: those that mutate the array they are applied to and those that process the array and return a new one, leaving the original array unchanged.

Methods that mutate the array

  1. push() — adds one or more elements to the end of the array. Returns the new length of the array.
  2. pop() — removes the last element of the array and returns it.
  3. shift() — removes the first element of the array and returns it.
  4. unshift(…elements) — adds one or more elements to the start of the array.
  5. splice(start, deleteCount ,…items, …items,…items) — adds, removes or replaces elements in the array at the specified index. Returns an array of removed elements.
  6. reverse() — reverses the order of the elements in the array. Returns a reference to the modified array.
  7. sort(compareFunction) — sorts the array elements (by default as strings). Returns a reference to the sorted array.
  8. fill(value, start, end) — fills all elements of the array from the start index to the end index with one value.
  9. copyWithin(target, start, end) – copies a sequence of array elements within the array from positions [start, end) to position target. Returns a reference to the modified array.

Methods that do not mutate the array

  1. concat() — returns a new array that is the result of concatenating two or more arrays.
  2. slice() — returns a new array that contains a copy of part of the original array.
  3. map() — returns a new array that is the result of applying a function to each element of the original array.
  4. filter() — returns a new array containing elements that meet the condition.
  5. reduce() — returns a single value that is the result of applying a function to each element of the array.
  6. reduceRight() — similar to reduce(), but processes the array from right to left.
  7. flat() — returns a new array with all sub-arrays “flattened” to the specified depth.
  8. flatMap() — combines map() and flat(), returns a new array.
  9. join() — returns a string that is the result of joining all elements of the array.
  10. indexOf() — returns the index of the first occurrence of an element in the array.
  11. includes() — checks if the array contains a certain element.
  12. find() — returns the first element that satisfies the provided function.
  13. findIndex() — returns the index of the first element that satisfies the provided function.
  14. some() — checks if at least one element in the array satisfies the provided function.
  15. every() — checks if all elements in the array satisfy the provided function.
  16. sort() — sorts the array elements.
  17. toString() — returns the array as a string.
  18. valueOf() — returns the array itself.

Important:
Mutating methods change the original array, while non-mutating methods return a new array or value without changing the original array. This distinction is important when working with arrays.

Some methods in JavaScript arrays return a new array, while others modify the original array. Understanding these differences is important to avoid unexpected changes in your data. In this article, we will look at more detailed examples of array manipulations and various methods for working with arrays.

Additional methods for array processing

  1. find() — returns the first element in the array that satisfies the provided testing function.
  2. findIndex() — returns the index of the first element that satisfies the testing function.
  3. some() — checks if at least one element in the array passes the test implemented by the provided function.
  4. every() — checks if every element in the array passes the test implemented by the provided function.
  5. includes() — checks if a specific element is present in the array.
  6. indexOf() — returns the index of the first occurrence of the specified element in the array.
  7. toString() — returns a string representation of the array.
  8. join() — joins all elements of the array into a single string.

Common use cases

Arrays in JavaScript are often used to handle collections of data. Some common scenarios for using arrays include:

  • Storing a list of items, such as products in an online store or students in a classroom.
  • Handling dynamic data that may change over time, such as the results of user input or real-time data feeds.
  • Managing ordered data, where the position of an element matters, such as a playlist or a queue.
  • Performing operations like filtering, sorting, or searching through the list of data.

Arrays in JavaScript offer many powerful methods for working with large sets of data. Whether you’re filtering results, performing calculations, or just storing simple values, arrays provide a flexible and efficient way to manage data. Understanding how to manipulate arrays using these methods is crucial for efficient JavaScript development.

We hope this overview of JavaScript array methods helps you gain a better understanding of how to work with arrays effectively. Happy coding!

Victoriia Hladka
Victoriia Hladka
https://victoriaweb.me