DEV Community

Cover image for JAVASCRIPT ARRAY METHODS: KNOW WHICH ONES YOU NEED TO KNOW
Higor Beleza
Higor Beleza

Posted on

JAVASCRIPT ARRAY METHODS: KNOW WHICH ONES YOU NEED TO KNOW

In programming, arrays store data while array methods help manage and modify this data based on the app's rules. Knowing these data structures and methods is vital for cleaner, organized, and more efficient code. In this article, we'll explore various methods and their usage by first understanding arrays and their associated methods

What is array?

In coding, arrays act like containers, holding multiple items in a neat package under one name. In JavaScript, arrays are versatile and function like a box where you can keep different things—like words, numbers, or even other boxes.

// An array storing various types of data
let myArray = ['apple', 42, true, { name: 'John' }];

// Accessing elements in the array
console.log(myArray[0]); // Output: 'apple'
console.log(myArray[1]); // Output: 42
console.log(myArray[3]); // Output: { name: 'John' }
Enter fullscreen mode Exit fullscreen mode

What is a method in JavaScript?

Methods are like built-in tools that help us do things with objects, like arrays, strings, and objects themselves.

In JavaScript, methods work like commands in a toolbox. For example, the push() method acts like a tool to add new things to an array. To use push(), you just call it on an array you already have using the dot.

// Creating an array
let fruits = ['apple', 'banana', 'orange'];

// Using the push() method to add a new element to the array
fruits.push('grape');

// Displaying the updated array
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'grape']

Enter fullscreen mode Exit fullscreen mode

Array methods in JavaScript

here are some of the most common methods for manipulating and accessing elements in a JavaScript array:

.concat()

The concat() method in JavaScript is used to merge two or more arrays, creating a new array that contains the elements of the original arrays. It doesn't change the existing arrays; instead, it returns a new array containing a combination of the arrays provided as arguments to concat().

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let array3 = [7, 8, 9];

let newArray = array1.concat(array2, array3);

console.log(newArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen mode Exit fullscreen mode

concat() combines array1, array2, and array3 into a new array called newArray, without modifying the original arrays. It creates a single array with all the elements from the arrays provided in the concat() method, in the order they were passed as arguments.

.join()

The join() method is used to create a string from the elements of an array. It combines the array elements into a single string, separating each element with a specified separator. Here's an example of how to use the join() method:

let fruits = ['apple', 'banana', 'orange'];

// Joining array elements into a string separated by a comma
let result = fruits.join(', ');

console.log(result); // Output: 'apple, banana, orange'

Enter fullscreen mode Exit fullscreen mode

In this example, the join(', ') method call on the fruits array creates a string where each element is separated by a comma and a space, resulting in apple, banana, orange.

.push()

The .push() method in JavaScript is used to add one or more elements to the end of an array. When you invoke .push() on an array, it adds the specified element(s) to the end of the array and returns the new length of the array.

let fruits = ['apple', 'banana', 'orange'];

// Adding a new element to the end of the array
fruits.push('grape');

console.log(fruits); // Output: ['apple', 'banana', 'orange', 'grape']
Enter fullscreen mode Exit fullscreen mode

In this example, the .push('grape') method call adds the string grape to the end of the fruits array, extending the array's length and including the new element at the end.

.shift()

The .shift() method in JavaScript is used to remove the first element from an array and returns that removed element. It also updates the indexes of the remaining elements in the array, shifting them down to a lower index by one.

let fruits = ['apple', 'banana', 'orange'];

// Removing the first element from the array
let removedElement = fruits.shift();

console.log(removedElement); // Output: 'apple'
console.log(fruits); // Output: ['banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

In this example, fruits.shift() removes the first element 'apple' from the fruits array and returns it. After the operation, fruits contains ['banana', 'orange'].

.unshift()

The .unshift() method in JavaScript is used to add one or more elements to the beginning of an array. It modifies the original array by adding the specified element(s) to the front and returns the new length of the array.

let fruits = ['banana', 'orange'];

// Adding elements to the beginning of the array
let newLength = fruits.unshift('apple', 'grape');

console.log(newLength); // Output: 4 (new length of the array)
console.log(fruits); // Output: ['apple', 'grape', 'banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

In this example, .unshift('apple', 'grape') adds the strings 'apple' and 'grape' to the beginning of the fruits array. The resulting array is ['apple', 'grape', 'banana', 'orange'], and newLength holds the new length of the modified array, which is 4.

.slice()

The .slice() method in JavaScript is used to extract a portion of an array into a new array without modifying the original array. It takes in two optional parameters: the start index (inclusive) and the end index (exclusive) of the portion to be extracted. If no parameters are provided, .slice() will copy the entire array.

let fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];

// Using slice to create a new array
let slicedFruits = fruits.slice(1, 4);

console.log(slicedFruits); // Output: ['banana', 'orange', 'grape']
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'grape', 'kiwi']
Enter fullscreen mode Exit fullscreen mode

In this example, fruits.slice(1, 4) creates a new array slicedFruits containing elements from index 1 (inclusive) up to index 4 (exclusive) from the fruits array, returning ['banana', 'orange', 'grape']. The original fruits array remains unchanged. If no parameters were passed, .slice() would copy the entire array.

.splice()

The .splice() method in JavaScript is a versatile method used to modify the contents of an array by removing or replacing existing elements and/or adding new elements in place. It changes the original array and can return an array containing the removed elements.

Its syntax generally looks like this: array.splice(start, deleteCount, item1, item2, ...)

  • start: The index at which to start modifying the array.

  • deleteCount: The number of elements to remove starting from the start index.

  • item1, item2, ...: Optional. Elements to be added to the array at the start index.

let fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];

// Removing elements and adding new ones using splice
let removedElements = fruits.splice(2, 2, 'lemon', 'pear');

console.log(removedElements); // Output: ['orange', 'grape']
console.log(fruits); // Output: ['apple', 'banana', 'lemon', 'pear', 'kiwi']
Enter fullscreen mode Exit fullscreen mode

.reverse()

The .reverse() method in JavaScript is used to reverse the order of elements in an array. It modifies the original array by rearranging the elements to appear in the opposite order.

let fruits = ['apple', 'banana', 'orange', 'grape'];

// Reversing the order of elements in the array
fruits.reverse();

console.log(fruits); // Output: ['grape', 'orange', 'banana', 'apple']
Enter fullscreen mode Exit fullscreen mode

In this example, fruits.reverse() reverses the order of elements in the fruits array. After the operation, the original order of ['apple', 'banana', 'orange', 'grape'] is reversed to ['grape', 'orange', 'banana', 'apple'].

Conclution

JavaScript's array methods offer powerful tools for managing and retrieving elements in lists. Throughout this piece, we've delved into several key methods like concat(), join(), push(), pop(), shift(), unshift(), slice(), splice(), and reverse(). Each of these serves a unique purpose and proves invaluable depending on the task at hand.

While employing these methods, it's key to note that certain ones directly change the original array, whereas others provide a modified copy without altering the initial array. Take time to review the documentation thoroughly to grasp how each method operates and its specific effect on the original array.

Top comments (0)