JavaScript

How to add an element to the beginning of an array in JavaScript

You can use the unshift() method to easily add new elements or values to the beginning of an array in JavaScript. This method does the reverse of the push() method, which adds the elements to the end of an array.

The following example will show you how to add one or more elements to the beginning of an array.
 

How to add an element to the beginning of an array in JavaScript
var languages = ["JavaScript", "HTML", "CSS"];
 
// Add "PHP" to the beginning of languages array
languages.unshift("PHP");
 
console.log(languages);
// Output: ["PHP", "JavaScript", "HTML", "CSS"]
 
// Add multiple values to the beginning of languages array
languages.unshift("Java", "Python");
 
console.log(languages);
// Output: ["Java", "Python", "PHP", "JavaScript", "HTML", "CSS"]
 
// Display the array of languages and display all the values
for(var i = 0; i < languages.length; i++){
    document.write("" + languages[i] + "");
}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *