JavaScript .unshift()

Anonymous contributor's avatar
Anonymous contributor
Published Jun 21, 2021Updated Jun 12, 2023
Contribute to Docs

Adds one or more elements to beginning of array and returns new length.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

Syntax

array.unshift(item1, item2, ...);

Examples

To add the element 'Monday' to the daysOfWeek array:

const daysOfWeek = [
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
daysOfWeek.unshift('Monday');
console.log(daysOfWeek);
// Output: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

To add elements 1 and 2 to the countToTen array:

const countToTen = [3, 4, 5, 6, 7, 8, 9, 10];
countToTen.unshift(1, 2);
console.log(countToTen);
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Codebyte Example

The code below adds Lemon and Pineapple to the beginning of the array fruits with the help of the .unshift() method.

Code
Output

All contributors

Contribute to Docs

Learn JavaScript on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours