JavaScript slice() & splice() Method
slice() selects the specified number of elements without affecting the original array elements whereas splice() removes the selected elements from the original array itself.
Example: In this example, we will see the use of the slice() and splice() methods.
let arr = [1, 2, 3, 4, 5];
let sliceArray = arr.slice(0, 2);
console.log("Slice Array: " + sliceArray);
console.log("Original Array: " + arr);
let spliceArray = arr.splice(0, 2);
console.log("Slice Array: " + spliceArray);
console.log("Original Array: " + arr);
Output
Slice Array: 1,2 Original Array: 1,2,3,4,5 Slice Array: 1,2 Original Array: 3,4,5
What are the Important Array Methods of JavaScript ?
In this article, we will try to understand various important Array methods (like push(), pop(), and so on) with the help of certain examples.
Let us first understand how we can create an array in JavaScript by using certain syntax provided.
Syntax:
let array = [element1, element2, .....]
Alternatively, we may also use the Array class (using a new keyword along with the Array class default constructor) for creating new Array elements, but it is always recommended that we must prefer using the above literal syntax.
let array = new Array (element1, elemnet2, .....);
Example: In this example, we will create an array using both the methods discussed above.
let array = ['Hello',
'w3wiki', 'JavaScript'];
console.log(array);
let newArray = new Array('Hello',
'w3wiki', 'JavaScript');
console.log(newArray);
Output:
['Hello', 'w3wiki', 'JavaScript']
['Hello', 'w3wiki', 'JavaScript']
Now that we have understood the creation of an array with the help of an example, let us now jump into several methods which are associated with the array.
JavaScript Array Methods:
Table of Content
- JavaScript push() Method
- JavaScript pop() Method
- JavaScript shift() Method
- JavaScript unshift() Method
- JavaScript indexOf() Method
- JavaScript includes() Method
- JavaScript concat() Method
- JavaScript forEach() Method
- JavaScript sort() Method
- JavaScript map() method
- JavaScript reduce() Method
- JavaScript filter() Method
- JavaScript find() & findIndex() Method
- JavaScript slice() & splice() Method
- JavaScript some() and every() Method
- Javascript forEach() method
- JavaScript Array reverse() Method
- Javascript Array every() method