How do I append an object (such as a string or number) to an array in JavaScript?
You can use the push method to append elements to an array in JavaScript. Here’s an example:
push
// Create an array let myArray = [1, 2, 3]; // Append a string to the array myArray.push("four"); // Append a number to the array myArray.push(5); console.log(myArray); // Output: [1, 2, 3, "four", 5]
In this example, the push method is used to add elements to the end of the array. You can append multiple elements at once by passing them as arguments to the push method:
// Append multiple elements to the array myArray.push("six", 7); console.log(myArray); // Output: [1, 2, 3, "four", 5, "six", 7]
If you want to append elements to the beginning of the array, you can use the unshift method:
unshift
// Append elements to the beginning of the array myArray.unshift("zero", -1); console.log(myArray); // Output: ["zero", -1, 1, 2, 3, "four", 5, "six", 7]
Choose push or unshift based on whether you want to add elements to the end or the beginning of the array, respectively.