CodeDancing with Milos
· 4 Min read

Dancing with Arrays in JavaScript!

Arrays are essential in programming, providing a flexible way to store and manage ordered data. This guide explores JavaScript arrays, covering their declaration, manipulation, and iteration techniques.

Post

Learning Goals

By the end of this post, you will be able to:

  • Define arrays in JavaScript and describe their purpose and flexibility.
  • Explain how arrays can store different data types and how elements are accessed by index.
  • Demonstrate how to declare arrays, add or remove elements, and use basic operations.
  • Utilize JavaScript array methods for adding, removing, and transforming elements, such as push, pop, shift, unshift, splice, slice, concat, join, reverse, and sort.
  • Identify array methods that simplify data searching, including indexOf, lastIndexOf, and includes.
  • Apply array methods for iteration, like forEach, map, filter, reduce, reduceRight, some, every, find, and findIndex.
  • Recognize practical applications of arrays and how array manipulation can streamline complex data tasks, such as processing API responses or filtering lists.

Introduction to Arrays

At their core, arrays in JavaScript are used to store ordered collections of elements. These elements can be accessed by their index, starting from zero. Arrays are declared using square brackets [], and their size can dynamically change, allowing elements to be added or removed as needed.

Declaration and Basic Operations

Here's how you can declare an array and perform basic operations:

js/main.js
// Declaring an array
let fruits = ["Apple", "Banana", "Cherry"];
 
// Accessing elements
console.log(fruits[1]); // Outputs: Banana
 
// Replacing an element
fruits[1] = "Blueberry";
console.log(fruits); // Outputs: ["Apple", "Blueberry", "Cherry"]
 
// Adding a new element
fruits.push("Durian");
console.log(fruits); // Outputs: ["Apple", "Blueberry", "Cherry", "Durian"]
 
// Array length
console.log(fruits.length); // Outputs: 4

Arrays can store elements of any type, from numbers and strings to objects and even other arrays. This flexibility, combined with the ability to iterate over array elements, makes them an indispensable tool in a developer's arsenal.


Array Methods

JavaScript arrays come equipped with a suite of methods for performing various operations, such as adding, removing, and transforming elements.

Adding and Removing Elements

  1. push()
  • Adds an element to the end of the array and returns the new length of the array.
js/main.js
let numbers = [1, 2, 3];
let newLength = numbers.push(4); // newLength is 4
console.log(numbers); // Outputs: [1, 2, 3, 4]
  1. pop()
  • Removes the last element from an array and returns that element.
js/main.js
let numbers = [1, 2, 3];
let lastElement = numbers.pop(); // lastElement is 3
console.log(numbers); // Outputs: [1, 2]
  1. shift()
  • Removes the first element from an array and returns that element.
js/main.js
let numbers = [1, 2, 3];
let firstElement = numbers.shift(); // firstElement is 1
console.log(numbers); // Outputs: [2, 3]
  1. unshift()
  • Adds one or more elements to the beginning of an array and returns the new length of the array.
js/main.js
let numbers = [2, 3];
let newLength = numbers.unshift(0, 1); // newLength is 4
console.log(numbers); // Outputs: [0, 1, 2, 3]
  1. splice()
  • Adds or removes elements from an array at a specified index.
js/main.js
let numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 1); // Removes one element at index 2
console.log(numbers); // Outputs: [1, 2, 4, 5]
  1. slice()
  • Returns a shallow copy of a portion of an array into a new array object.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let slicedNumbers = numbers.slice(1, 4); // slicedNumbers is [2, 3, 4]
console.log(slicedNumbers);
  1. concat()
  • Merges two or more arrays and returns a new array.
js/main.js
let numbers1 = [1, 2];
let numbers2 = [3, 4];
let mergedNumbers = numbers1.concat(numbers2); // mergedNumbers is [1, 2, 3, 4]
console.log(mergedNumbers);
  1. join()
  • Joins all elements of an array into a string.
js/main.js
let fruits = ["Apple", "Banana", "Cherry"];
let fruitsString = fruits.join(", "); // fruitsString is "Apple, Banana, Cherry"
console.log(fruitsString);
  1. reverse()
  • Reverses the elements of an array in place.
js/main.js
let numbers = [1, 2, 3];
numbers.reverse();
console.log(numbers); // Outputs: [3, 2, 1]
  1. sort()
  • Sorts the elements of an array in place.
js/main.js
let fruits = ["Banana", "Apple", "Cherry"];
fruits.sort();
console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry"]
  1. indexOf()
  • Returns the first index at which a given element can be found in the array, or -1 if it is not present.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let index = numbers.indexOf(3); // index is 2
console.log(index);
  1. lastIndexOf()
  • Returns the last index at which a given element can be found in the array, or -1 if it is not present.
js/main.js
let numbers = [1, 2, 3, 4, 3];
let lastIndex = numbers.lastIndexOf(3); // lastIndex is 4
console.log(lastIndex);
  1. includes()
  • Determines whether an array includes a certain element, returning true or false as appropriate.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let includesThree = numbers.includes(3); // includesThree is true
console.log(includesThree);

Array Methods for Looping

  1. forEach()
  • Executes a provided function once for each array element.
js/main.js
let numbers = [1, 2, 3];
numbers.forEach((number) => {
  console.log(number);
});
  1. map()
  • Creates a new array with the results of calling a provided function on every element in the array.
js/main.js
let numbers = [1, 2, 3];
let squaredNumbers = numbers.map((number) => number * number);
console.log(squaredNumbers); // Outputs: [1, 4, 9]
  1. filter()
  • Creates a new array with all elements that pass the test implemented by the provided function.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter((number) => number % 2 === 0);
console.log(evenNumbers); // Outputs: [2, 4]
  1. reduce()
  • Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Outputs: 15
  1. reduceRight()
  • Applies a function against an accumulator and each element in the array (from right to left) to reduce it to a single value.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Outputs: 15
  1. some()
  • Tests whether at least one element in the array passes the test implemented by the provided function.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let hasNegativeNumbers = numbers.some((number) => number < 0);
console.log(hasNegativeNumbers); // Outputs: false
  1. every()
  • Tests whether all elements in the array pass the test implemented by the provided function.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let allPositiveNumbers = numbers.every((number) => number > 0);
console.log(allPositiveNumbers); // Outputs: true
  1. find()
  • Returns the value of the first element in the array that satisfies the provided testing function.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let firstEvenNumber = numbers.find((number) => number % 2 === 0);
console.log(firstEvenNumber); // Outputs: 2
  1. findIndex()
  • Returns the index of the first element in the array that satisfies the provided testing function.
js/main.js
let numbers = [1, 2, 3, 4, 5];
let firstEvenNumberIndex = numbers.findIndex((number) => number % 2 === 0);
console.log(firstEvenNumberIndex); // Outputs: 1

These looping methods provide powerful tools for processing and transforming data stored in arrays. By choosing the appropriate method for the task at hand, you can write more efficient, readable, and functional JavaScript code.


Practical Applications

Understanding and utilizing these array methods allows for cleaner code and more expressive implementations of data manipulation tasks. For example, transforming data retrieved from an API, filtering lists based on user input, or calculating aggregates from sets of numbers become straightforward tasks.

Conclusion

Arrays in JavaScript are versatile and powerful, offering a wide range of methods for manipulation and iteration. By mastering these methods, you can handle complex data structures more effectively, leading to more maintainable and readable code. Whether you're adding or removing elements, searching, or iterating through arrays, JavaScript provides a method that suits your needs, making it an essential part of the language for developers.


P.S. Want to become a better Frontend Web Engineer? 👩💻👨💻

Subscribe to the branded new CodeDancing with Milos newsletter and get two practical articles every week.

Follow me on LinkedIn.

Copyright © CodeDancingwithMilos. All rights reserved.