Welcome to TagMyCode

Please login or create account to add a snippet.
Language: Javascript
Posted by: Lelana villa
Added: Mar 23, 2018 7:45 PM
Views: 1
Tags: no tags
Creates a new array based on the elements in the current array. It's important to know that the original array is not altered. The operation is made on the copy of that array. concat() accepts any number of arguments which will be added at the end of the array. Using it without arguments is a elegent way to clone the initial array.

Similar to concat(), slice creates a copy of the array and extracts a subsequence of it. Used with no parameters, it returns a copy of the original. With one argument - index -, returns all elements from that index to the end. Additionally, it can be used with 2 arguments - start_index and end_index, in which case it will return all elements in that interval (excluding the one from last_index).

The function can be used with a negative value as parameter. In this case, the start index will be counted from the end of the array - start_index = array.length - param

Splice() has very similar use cases like concat() and splice(), the only difference is that the operation is made on the original array.

It's a destructive method, you won't be able to revert it, so be careful to that when using it.

It can take more arguments splice(start_index, number_of_deleted_items, element1, element2, .... elementN). In this case, starting from start_index, it will delete the number of items specified on the second argument. The elements element1, element2..elementN will be added, in this order to the array. Basically, you replace a number of items with the elements you provide.

The function returns an array with the deleted items.

You can adapt the behavior as you wish. For example splice(start_index, number_of_deleted_items) for deleting elements or splice(start_index, 0, item_to_insert) for inserting without deleting.
  1. var arr = [true, 2, 3, "4"];
  2. new_array = arr.concat(5, 6, 7)
  3. console.log(new_array);         // [true, 2, 3, "4", 5, 6, 7]
  5. new_array = arr.slice(0, 2);
  6. console.log(new_array);         // [true, 2]
  8. console.log(arr);               // arr not changed - [true, 2, 3, "4"]
  9. arr.splice(0, 1, 1); // I replace the first item with 1
  10. console.log(arr);                // [1, 2, 3, "4"]