Q:

How to Add New Elements at the Beginning of an Array in JavaScript

0

How to Add New Elements at the Beginning of an Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the unshift() Method

You can use the unshift() method to easily add new elements or values at the beginning of an array in JavaScript. This method is a counterpart of the push() method, which adds the elements at the end of an array. However, both method returns the new length of the array.

The following example will show you how to add single or multiple elements at the start of an array.

<script>
var fruits = ["Apple", "Banana", "Mango"];
    
// Prepend a single element to fruits array
fruits.unshift("Orange");
    
console.log(fruits);
// Prints: ["Orange", "Apple", "Banana", "Mango"]
    
// Prepend multiple elements to fruits array
fruits.unshift("Guava", "Papaya");
    
console.log(fruits);
// Prints: ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]
    
// Loop through fruits array and display all the values
for(var i = 0; i < fruits.length; i++){
    document.write("<p>" + fruits[i] + "</p>");
}
</script>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the Value of Text Input Field Using Jav... >>
<< How to Convert JS Object to JSON String...