Skip to content

JavaScript append to list | Example code

  • by

Use the Array.prototype.push method to append values to the end of a List (array) in JavaScript.

Read more: JavaScript append to Array | 5 Ways With example code

JavaScript append to list

Simple example code append new value to the array (list).

<!DOCTYPE html>
<html>
<body>

  <script>

   var arr = [
   "Hi",
   "Hello",
   "Bonjour"
   ];

   arr.push("Hola");

   console.log(arr);
 </script>

</body>
</html> 

Output:

JavaScript append to list

You can use the push() function to append more than one value to an array in a single call:

// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];

// append multiple values to the array
arr.push("Salut", "Hey");

// display all values
for (var i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

var arr = [
  "apple",
  "banana",
  "cherry"
];

// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);

if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.

var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);

Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged but returns a new array with new items appended, compliant with the spirit of functional programming.

const arr = [
  "Hi",
  "Hello",
  "Bonjour",
];

const newArr = [
  ...arr,
  "Salut",
];

console.log(newArr);

Source: stackoverflow.com

Do comment if you have doubts or suggestions on this Js list topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading