Site menu

CodeCook.io

  • Languages
    • C
    • C++
    • CSS
    • Git
    • HTML
    • Java
    • JavaScript
    • jQuery
    • PHP
    • Python
    • Ruby
    • Scala
  • array
  • prepend

JavaScript - Prepend item to array

Add item to front of an array.

0
2823
  • Share on Facebook
  • Share on Google+
  • Share on Twitter

Using Array.prototype.unshift

Add element (or elements) to front of array. The length of the resulting new array is returned.

{{array}}.unshift({{item}})
javascript
  • unshift

Notes

  • Modifies original array.
new length [integer]

last update: Feb. 8, 2015

0
2897
  • Share on Facebook
  • Share on Google+
  • Share on Twitter

Unshift array preserving original array

Creates a shallow copy of array and prepends item to the copied array.

{{array}}.slice(0).unshift({{item}});
javascript
  • slice
  • unshift

Notes

  • Original array remains intact.
  • Slower than version that mutates array.
new length [integer]

last update: Feb. 8, 2015

Advertisement

This project is hosted on DigitalOcean, try it and support us

Similar

  • Prepend item to list

Related concept

  • Create empty array
  • Find index of item in array
  • Map over array
  • Array length
  • Append item to array
  • Concatenate two arrays

Random task

  • Export module
  • Change git remote tracking branch
  • If, else if, else
  • HTTP Get REST endpoint
  • Select dom elements by tag
  • Blog
  • About
  • License