unshift() Method in JavaScript

JavaScript1 min read
unshift() Method in JavaScript
javascriptunshift methodarray method

unshift() is a built-in method in JavaScript that adds one or more elements to the beginning of an array.

unshift() Methods in JavaScript

  • unshift() is a built-in method in JavaScript that adds one or more elements to the beginning of an array.
  • It modifies the original array and returns the new length of the array.
  • The existing elements in the array will be shifted to higher indexes to accommodate the new elements.

Example:

  • Let's take an array notifications, with elements like notification-2 and notification-1.
let notifications = ['notification-2', 'notification-1'];

To show all notifications, use the forEach() method.

let notifications = ['notification-2', 'notification-1']; notifications.forEach(item => { document.write(item + "<br>"); }); // Output: notification-2 notification-1

Now, all the notifications in the array are displayed as notification-2, notification-1.

  • If you want to add a new notification to the beginning of the array, use the unshift() method:
let notifications = ['notification-2', 'notification-1']; notifications.unshift('notification-3'); notifications.forEach(item => { document.write(item + "<br>"); }); // Output: notification-3 notification-2 notification-1

Now, notification-3 is added to the beginning of the notifications array.

  • If you want to add more than one notification to the beginning of the array, pass multiple items to the unshift() method:
let notifications = ['notification-2', 'notification-1']; notifications.unshift('notification-3'); notifications.unshift('notification-5', 'notification-4'); notifications.forEach(item => { document.write(item + "<br>"); }); // Output: notification-5 notification-4 notification-3 notification-2 notification-1

Now, notification-5 and notification-4 are added to the beginning of the notifications array.

  • Like this, we can add elements to the beginning of an array using the unshift() method.