JavaScript Glossary - Lesson #18

JavaScript Array .unshift() Method

The unshift array method appends a number of values to the start of a given array. It then returns the new length of the array. This method can take a number of arguments, each to be added to the array in the specified order.

js
[1, 2, 3, 4, 5].unshift(0, 0.5)
// [0, 0.5, 1, 2, 3, 4, 5]
js
// New Array
let array = [10, 20, 30, 40, 50]

// Add new numbers to start of the array
let newLength = array.unshift(2, 5)

// Display new length and old array
console.log(newLength) // 7 
console.log(array) // [2,5,10,20,30,40,50]

Unshift mutates the original array and returns the length of the original array after the mutation.

js
const newArray = oldArray.unshift(item1, item2, ...itemN)

item[s] This is the element or multiple elements or items to be added.

The method will return the length of the array after adding the new elements.

Adding new values to the start of an array maintaining a set order.

js
// Array of items
const items = ['Cedar', 'Fruits', 'Table'];

// Add new items to array
items.unshift('wine', 'glass');

// Display modified array
console.log(items); // ["wine","glass","Cedar","Fruits","Table"]

The unshift() method can be used to add new items to the front of an array of objects.

js
// Array of objects in cart
const cart = [
  {
    item: "bread",
    price: 2000,
  },
  {
    item:"milk",
    price: 1000
  }
]

// Add item to cart
cart.unshift({item: "eggs", price: 500})

// Display modified array
console.log(cart) // [{"item":"eggs","price":500},{"item":"bread","price":2000},{"item":"milk","price":1000}]

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)