Posts

Showing posts with the label javascript array methods

Common Array methods in JavaScript that modify the array in place

The following are the common array methods in JavaScript that modify the original array instead of returning a new one: 1. pop():  Removes and returns the last element from an array. Example: myArray.pop(); 2. push():  Adds one or more elements to the end of an array and returns the new length of the array. Example: myArray.push(element1, element2); 3. shift():  Removes and returns the first element from an array. Example: myArray.shift(); 4. unshift():   Adds one or more elements to the beginning of an array and returns the new length of the array. Example: myArray.unshift(element1, element2); 5. splice():  This is a versatile method that can be used to: Remove elements from an array (splice(start, deleteCount)) Add elements to an array (splice(start, 0, element1, element2)) Replace elements in an array (splice(start, deleteCount, element1, element2)) Example: myArray.splice(2, 1); // Removes one element at index 2 myArray.splice(1, 0, 'newElement'); // Adds 'newElement