- Array.prototype.push()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Adding elements to an array
- Merging two arrays
- Calling push() on non-array objects
- Using an object in an array-like fashion
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- JavaScript List Append: Different Methods and Best Practices
- The push() method
- The unshift() method
- Other ways to add items to an array
- Adding items to a list in HTML
- Best practices and tips
- Additional helpful code examples for appending items to a list in JavaScript
- Conclusion
- Add & Remove List Items In Javascript (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- JAVASCRIPT LIST ITEMS
- 1) CREATE LIST ITEM ELEMENT & APPEND
- 2) APPEND POSITION
- 3) ALTERNATIVE – APPEND HTML STRING
- 4) REMOVE LIST ITEM
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
Array.prototype.push()
The push() method adds the specified elements to the end of an array and returns the new length of the array.
Try it
Syntax
push() push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN)
Parameters
The element(s) to add to the end of the array.
Return value
The new length property of the object upon which the method was called.
Description
The push() method appends values to an array.
Array.prototype.unshift() has similar behavior to push() , but applied to the start of an array.
The push() method is a mutating method. It changes the length and the content of this . In case you want the value of this to be the same, but return a new array with elements appended to the end, you can use arr.concat([element0, element1, /* . ,*/ elementN]) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of concat() .
The push() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
Adding elements to an array
The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.
const sports = ["soccer", "baseball"]; const total = sports.push("football", "swimming"); console.log(sports); // ['soccer', 'baseball', 'football', 'swimming'] console.log(total); // 4
Merging two arrays
This example uses spread syntax to push all elements from a second array into the first one.
const vegetables = ["parsnip", "potato"]; const moreVegs = ["celery", "beetroot"]; // Merge the second array into the first one vegetables.push(. moreVegs); console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
Merging two arrays can also be done with the concat() method.
Calling push() on non-array objects
The push() method reads the length property of this . It then sets each index of this starting at length with the arguments passed to push() . Finally, it sets the length to the previous length plus the number of pushed elements.
const arrayLike = length: 3, unrelated: "foo", 2: 4, >; Array.prototype.push.call(arrayLike, 1, 2); console.log(arrayLike); // const plainObj = >; // There's no length property, so the length is 0 Array.prototype.push.call(plainObj, 1, 2); console.log(plainObj); //
Using an object in an array-like fashion
As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.
Note that we don’t create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.
const obj = length: 0, addElem(elem) // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem); >, >; // Let's add some empty objects just to illustrate. obj.addElem(>); obj.addElem(>); console.log(obj.length); // 2
Note that although obj is not an array, the method push successfully incremented obj ‘s length property just like if we were dealing with an actual array.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 19, 2023 by MDN contributors.
Your blueprint for a better internet.
JavaScript List Append: Different Methods and Best Practices
Learn how to append items to a list in JavaScript using the push(), unshift(), concat(), spread operator, and more. Get helpful tips and best practices to avoid common errors.
- The push() method
- The unshift() method
- Other ways to add items to an array
- Adding items to a list in HTML
- Best practices and tips
- Additional helpful code examples for appending items to a list in JavaScript
- Conclusion
- How append items to list in JS?
- How to add an item to the end of a list in JavaScript?
- What is a way to append a value to an array in JavaScript?
- Can you use .append on an array?
JavaScript is an extremely popular programming language used in web development, and one of the most common tasks in JavaScript is adding an item to a list or an array. In this blog post, we will explore the different ways to append an item to a list in JavaScript and provide helpful tips and best practices to avoid common errors.
The push() method
The push() method is a built-in JavaScript function that adds one or more elements to the end of an array and returns the new length of the array. To add an element to an array using the push method, use the syntax array.push(item) . The push() method can accept an unlimited number of arguments, making it easy to add multiple items to an array at once. It is important to note that the push() method changes the length of the array and returns the new length.
let fruits = ["apple", "banana", "orange"]; fruits.push("grape"); console.log(fruits); // Output: ["apple", "banana", "orange", "grape"]
The unshift() method
The unshift() method is similar to the push() method, but instead of adding an item to the end of an array, it adds one or more elements to the beginning of an array and returns the new length of the array. To add an element to an array using the unshift() method, use the syntax array.unshift(item) . Like the push() method, the unshift() method changes the length of the array.
let fruits = ["apple", "banana", "orange"]; fruits.unshift("grape"); console.log(fruits); // Output: ["grape", "apple", "banana", "orange"]
Other ways to add items to an array
The concat() method can be used to append two or more arrays together, creating a new array. The spread operator (…) can also be used to append one array to another, creating a new array. The splice() method can be used to insert an item into an array at a specific index. It is important to note that these methods can overwrite existing elements in the array, so it is recommended to use the push() method to add an item to the end of an array.
let fruits = ["apple", "banana", "orange"]; let moreFruits = ["grape", "kiwi"];// Using the concat() method let allFruits = fruits.concat(moreFruits); console.log(allFruits); // Output: ["apple", "banana", "orange", "grape", "kiwi"]// Using the spread operator let allFruits = [. fruits, . moreFruits]; console.log(allFruits); // Output: ["apple", "banana", "orange", "grape", "kiwi"]// Using the splice() method fruits.splice(1, 0, "grape"); console.log(fruits); // Output: ["apple", "grape", "banana", "orange"]
Adding items to a list in HTML
The append() method is used to add an item to a list in HTML. To use the append() method, select the list element using JavaScript and call the append() method with the item you want to add as a parameter. It is important to note that the append() method only works with list elements in HTML.
ul id="fruits-list"> li>Appleli> li>Bananali> li>Orangeli> ul>script> let fruitsList = document.getElementById("fruits-list"); let newFruit = document.createElement("li"); newFruit.textContent = "Grape"; fruitsList.append(newFruit); script>
Best practices and tips
It is important to understand the difference between the push() and unshift() methods before using them. It is recommended to use the push() method to add an item to the end of an array. To avoid overwriting existing elements in an array, use the spread operator (…) or the slice() method to append one array to another. Cheatsheets can be helpful for beginners to quickly reference frequently used functions and methods in JavaScript.
Additional helpful code examples for appending items to a list in JavaScript
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); // Fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
In javascript, javascript add item to list code example
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi");
In javascript, javascript append list to list code example
a.push(. b);var a = [1,2,3]; var b = [4,5,6]; a.push(. b); // [1,2,3,4,5,6]// The .push method can take multiple arguments. // You can use the spread operator (. ) to pass all // the elements of the second array as arguments to .push
In javascript, javascript add item in list code example
ul li < list-style: none; border-style:groove; border-radius: 40px; >ul li:hover villes:
Conclusion
Adding an item to a list or an array is a common task in JavaScript, and there are many ways to do it. The push() method is the most commonly used method to add an item to the end of an array, while the append() method is used to add an item to a list in HTML. Understanding the different methods and best practices can help avoid common errors and make the process of appending items to a list or an array in JavaScript more efficient.
Add & Remove List Items In Javascript (Simple Examples)
Welcome to a quick tutorial on how to add and remove list items in Javascript. Need to dynamically update an HTML list in Javascript?
- To add a list item in Javascript:
- var li = document.createElement(«li»);
- li.innerHTML = «Item»;
- document.getElementById(«myList»).appendChild(li);
- var myList = document.getElementById(«myList»);
- var items = document.querySelectorAll(«#myList li»);
- Remove first item – myList.removeChild(items[0]);
- Remove last item – myList.removeChild(items[items.length — 1]);
That covers the basics, but read on for more examples!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
JAVASCRIPT LIST ITEMS
All right, let us now get into the examples of how to add and remove HTML list items in Javascript.
1) CREATE LIST ITEM ELEMENT & APPEND
This is the “full example” of the snippet in the introduction. Add new items to an HTML list is that simple – Just create a new list item, and append it to the list.
2) APPEND POSITION
The previous example will always append the new list item to the bottom of the list. So how do we insert to the top or somewhere in the middle? Use insertAdjacentElement() to help you do the “precise insert”.
3) ALTERNATIVE – APPEND HTML STRING
For you guys who somehow don’t like the “object-oriented” way of creating HTML elements – We can also directly append an HTML string to the existing list.
4) REMOVE LIST ITEM
- Get all the list items – var all = document.querySelectorAll(«#LIST li») .
- var all is an HTML collection of all the list items, and it acts like an array. I.E. all[0] refers to the first item, and all[all.length — 1] refers to the last item.
- So very simply, we just remove the corresponding item from the list itself – document.getElementById(«#LIST»).removeChild(all[N]) .
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.