YouTip LogoYouTip

Jsref Unshift

# JavaScript unshift() Method --- ## Definition and Usage The unshift() method adds new items to the beginning of an array, and returns the new length. **Tip:** You can add one or more items at the beginning of an array. **Tip:** Use the [push()]( method to add items at the end of an array. --- ## Browser Support | Method | Chrome | IE | Firefox | Safari | Opera | |---|---|---|---|---|---| | unshift() | Yes | Yes | Yes | Yes | Yes | --- ## Syntax ``` array.unshift(item1, item2, ..., itemX) ``` ## Parameters | Parameter | Description | |---|---| | item1, item2, ..., itemX | Required. The item(s) to add to the beginning of the array | ## Return Value | Type | Description | |---|---| | Number | The new length of the array | ## Technical Details | JavaScript Version: | ECMAScript 1 | |---|---| | Update History | IE 5.5, Firefox 4, Chrome, Opera, and Safari all support unshift() method | --- ## More Examples ### Example 1 Add a new item to the beginning of an array: ```html

Click the button to add elements to the beginning of the array.

function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon","Pineapple"); var x = document.getElementById("demo"); x.innerHTML = fruits; } ``` ### Example 2 Demonstrate the return value: ```html

Click the button to add elements to the beginning of the array.

function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = fruits.unshift("Lemon","Pineapple"); var text = "New Array: " + fruits + "
" + "Length of the array is: " + x; document.getElementById("demo").innerHTML = text; } ``` ### Example 3 Compare with push() method: ```html

Click the button to add elements to the array.

function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myArray() { fruits.push("Kiwi"); var x = document.getElementById("demo"); x.innerHTML = fruits; } } ```
← Jsref Valueof ArrayJsref Tostring Array β†’