Table of contents
Text Link

JavaScript Array Slicing Techniques

Arrays are a fundamental data structure in most programming languages, and JavaScript is no exception. An array is an ordered collection of values. Each value is called an element, and each element has a numeric position in the array, known as its index. JavaScript's arrays are untyped; an array element may be of any type, and different elements of the same array may be of various types. In reality, arrays help store elements of the same type—for example, an array of integers or strings.

For more curious readers, arrays in JS differ from what most would think of them or how the above definition describes them. See Coding Shorts: Objects and Arrays in JavaScript Might Not Be Real by Shawn Wildermuth to find out why.

There are many ways to manipulate arrays in JavaScript. One powerful technique, the slicing method, also known as the array slice method, allows developers to extract a portion of an array. This article will delve into slicing in JavaScript, explaining its syntax, uses and providing practical examples.

JavaScript Array Basics

An array in JavaScript is an object used to store multiple values in a single variable. You can create an array in JavaScript by declaring a variable and assigning it to a new Array object using the array literal syntax or with the Array.of() and Array.from() methods.

Example:

// Array Literals

// An array with no elements
let empty = [];

// An array with 5 numeric elements that are prime numbers
let primes = [2, 3, 5, 7, 11]; 

// An array with 10 numeric elements using the spread operator
let morePrimes = [...primes, 13, 17, 19, 23, 29];

// An array with 3 elements of different types
let anything = [1.1, 'one', true];

// An array with 3 elements, 2nd element is undefined
let threeElements = [1, , 3];

// Array Constructor

// An empty array, equivalent to []
let array1 = new Array();

// An array with 10 undefined elements
let array2 = new Array(10);

// Array.of and Array.from

// An array with three numeric elements
let numbers1 = Array.of(1, 2, 3);

// A copy (shallow) of the numbers array
let numbers2 = Array.from(numbers); 

What is Array Slicing?

Slicing in the context of arrays means getting a subset of elements from the original array. In JavaScript, you can do this using the slice() method.

let newArray = oldArray.slice(start, end);

The start and end parameters denote the count of elements you want to extract, where the start is inclusive and the end is exclusive. That means the slice starts from the index start and extracts elements up to (but not including) the index end.

Understanding Array.slice()

The slice function returns a new array containing a shallow copy of an array portion. The original one will remain the same.

let fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
let someFruits = fruits.slice(1, 3);

console.log(fruits); 
// Output: ['apple', 'banana', 'cherry', 'date', 'elderberry']

console.log(someFruits); 
// Output: ['banana', 'cherry']

In the example above, the slice function creates a new array of food items called someFruits containing elements from indexes 1 to 2 of the fruits array.

Special Cases

No parameters

If you call slice() without any optional parameters, it returns a copy of the original array:

let fruitsCopy = fruits.slice();

console.log(fruitsCopy); 
// Output: ['apple', 'banana', 'cherry', 'date', 'elderberry']

To achieve the same result, you can also use the spread operator (...):

let fruitsCopy2 = [...fruits];

or the array.from() method:

let fruitsCopy3 = Array.from(fruits)

Negative indices

You can use a negative index value to count from the end of the array. -1 refers to the last element, -2 refers to the second last, and so on:

let lastTwoFruits = fruits.slice(-2);

console.log(lastTwoFruits); 
// Output: ['date', 'elderberry']

One parameter

If you provide only one parameter detail, the slice() method will return elements from the start index to the end of the array.

let fromCherry = fruits.slice(2);

console.log(fromCherry); 
// Output: ['cherry', 'date', 'elderberry']

Performance Considerations

While slice() is a powerful method, it's important to note that it creates a new array. If you work with large arrays, it can lead to significant memory usage. As such, use it carefully.

Array.splice() Method

Another JavaScript method that sounds similar but serves a different purpose—splice().

The splice() method changes the array's contents by removing or replacing existing elements or adding new ones. Use splice() to add new array items to an array, remove items from it, or combine both. Unlike slice(), splice() modifies the original array.

Here's an example of using splice():

let fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
fruits.splice(2, 0, 'cantaloupe');

console.log(fruits); 
// Output: ['apple', 'banana', 'cantaloupe', 'cherry', 'date', 'elderberry']

In this example, splice() starts at the 2nd index of the array, removes 0 elements, and adds cantaloupe at that position.

Slicing vs. Splicing

As we've seen, slicing and splicing are two different operations:

  • slice() is a non-destructive array slicing method that leaves the original one untouched and returns a new array with selected items.

  • splice() is a destructive method that changes the original array by adding, replacing, or removing items.

It's essential to understand the distinction and choose the appropriate method based on the needs of your program.

Conclusion

The slice() method in JavaScript is a powerful tool for extracting array portions. Understanding how to use it effectively results in concise and readable code. However, remember that slice() creates a new array, which can affect memory usage. Unlike splice(), it doesn't modify the original array. Always choose the appropriate method for your specific needs. Happy coding!

This article should serve as a comprehensive guide to slicing in JavaScript. Try these examples in your code and experiment with the slice() method to better understand its capabilities and usage. You can find my examples on the Sswietoniowski GitHub. You can check out Introduction to JavaScript on Hyperskill to get even more knowledge.

Related Hyperskill topics

Share this article
Get more articles
like this
Thank you! Your submission has been received!
Oops! Something went wrong.

Create a free account to access the full topic

Wide range of learning tracks for beginners and experienced developers
Study at your own pace with your personal study plan
Focus on practice and real-world experience
Andrei Maftei
It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.