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' at index 1

6. sort(): 

Sorts the elements of an array in place and returns the modified array. The sorting order can be customized using a comparison function.

Example: myArray.sort(); // Sorts in ascending order myArray.sort((a, b) => b - a); // Sorts in descending order

7. reverse(): 

Reverses the order of the elements in an array in place and returns the modified array.

Example: myArray.reverse();

8. fill(): 

Fills all or part of an array with a static value.

Example: myArray.fill('default', 2); // Fills elements from index 2 onwards with 'default'


Important Note:

While these methods modify the original array, it's generally considered good practice to create a copy of the original array before using these methods if you need to preserve the original state for later use. You can use methods like slice() or the spread operator (...) to create copies.

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

The Basic Structure of a Full-Stack Web App

Unlocking Web Design: A Guide to Mastering CSS Layout Modes