In JavaScript, adding a new element to an array is a common operation. There are several ways to add an element to an array, including using the push()
method, the unshift()
method, or the splice()
method.
-
Push method
The
push()
method adds one or more elements to the end of an array. To add a single element to the end of an array, you can use thepush()
method with the value you want to add as an argument:const arr = [1, 2, 3]; arr.push(4); console.log(arr); // Output: [1, 2, 3, 4]
In this example, the
push()
method adds the value4
to the end of thearr
array. -
Unshift method
The
unshift()
method adds one or more elements to the beginning of an array. To add a single element to the beginning of an array, you can use theunshift()
method with the value you want to add as an argument:const arr = [2, 3]; arr.unshift(1); console.log(arr); // Output: [1, 2, 3]
In this example, the
unshift()
method adds the value1
to the beginning of thearr
array. -
Splice method
The
splice()
method can add elements to an array at a specific index. Thesplice()
method takes three arguments: the index where you want to start adding or removing elements, the number of elements you want to remove (0 if you only want to add elements), and the elements you want to add:const arr = [1, 2, 4, 5]; arr.splice(2, 0, 3); console.log(arr); // Output: [1, 2, 3, 4, 5]
In this example, the
splice()
method adds the value3
to thearr
array at index2
. The first argument (2
) specifies the index at which to begin adding or removing elements. The second argument (0
) specifies how many elements to remove. The third argument (3
) specifies the element(s) to add.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.