...

/

Replication with Array Methods

Replication with Array Methods

Overview of JavaScript methods to replicate and manipulate arrays.

Introduction

Given that arrays are mutable and cannot be copied by assigning them to new variables, copying is not so straightforward. Let’s go over methods to do so.

Replication via methods

Methods of an array are actions taken on the array itself. Let’s learn some methods to replicate and manipulate arrays further.

> slice()

The slice() method gets a copy of the array. This method can optionally pass values to specify the portion of the array to copy. By default, if no indices are specified, it copies the entire array. This method does not make any changes to the original array.

Press + to interact
var arr = [1, 2, 3, 4]; // Assign an array of elements to arr
// Print array along with it's type
console.log('Before Slice:');
console.log('arr:',arr);
// Call toString method and assign to str_arr
var arr1 = arr.slice();
var arr2 = arr.slice(1);
var arr3 = arr.slice(1,1);
var arr4 = arr.slice(0, -1);
// Print the type and values of arr and str_arr after calling toString method
console.log('After Slice:');
console.log(`original arr: ${arr}`);
console.log('arr1:', arr1);
console.log('arr2:', arr2);
console.log('arr3:', arr3);
console.log('arr4:', arr4);

The code above reveals some uses of the slice() method. The cases can be listed as follows:

  • No argument is specified (line 8
...