JAVASCRIPT Tutorial

unshift in JS

Definition:

'unshift' is a JavaScript method that adds one or more elements to the beginning of an array.

How to Use Unshift:

  1. Declare an Array: Create an array using square brackets [].
  2. Apply Unshift: Call the 'unshift' method on the array and pass the elements to be added as arguments.

Example:

let numbers = [2, 4, 6];
numbers.unshift(0, 1); // Adds 0 and 1 to the beginning

// Result: [0, 1, 2, 4, 6]

Key Concepts:

  • Elements: The elements to be added to the beginning of the array.
  • Modifies Original Array: 'unshift' modifies the original array, unlike slicing methods like 'slice' which create a new copy.
  • Returns New Length: The 'unshift' method returns the new length of the modified array.

Tips:

  • You can add multiple elements at once by passing them as individual arguments.
  • 'unshift' operates on arrays only. For other data structures like strings, you can use 'splice' to insert elements.

Conclusion:

'unshift' is a useful method for conveniently adding elements to the beginning of an array. It is simple to use and modifies the original array directly.