Member-only story
In JavaScript, you can add elements to an array using various methods. In this tutorial, we’ll explore how to add elements to an array in JavaScript with some examples.
Not a Medium member? Read this article here
- Adding Elements to an Array using Push()
One of the simplest ways to add an element to an array in JavaScript is to use the push()
method. The push()
method adds one or more elements to the end of an array and returns the new length of the array.
Here’s an example of how to add elements to an array using push()
:
const numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // Output: [1, 2, 3, 4]
numbers.push(5, 6);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
In this example, we have an array of numbers and we use the push()
method to add a single element and multiple elements to the end of the array.
2. Adding Elements to an Array using Splice()
The splice()
method can also be used to add elements to an array in JavaScript. The splice()
method adds or removes elements from an array at a specified index.
Here’s an example of how to add elements to an array using splice()
:
const colors = ['red', 'green', 'blue'];
colors.splice(1…