The push()
method in JavaScript adds new items to the end of an array. It also changes the length of the array and returns the value of the length of the new array.
array.push(item1, ..., itemN)
The push()
method takes the following parameter:
item1, ..., itemN
: these are the items to be added to the array.The function returns the value of the length of the new array.
// creating arrayslet array1 = [1, 2, 3];let array2 = ["a", "b", "c"];let array3 = ["Java", "C++", "Perl"]// pushing elements to arraylet A = array1.push(4, 5);let B = array2.push("d", "e");let C = array3.push("Ruby", "Javascript")// printing thier values to the console.console.log(A)console.log(B)console.log(C)// Printing the arrays to consoleconsole.log(array1)console.log(array2)console.log(array3)
In the code above, we see that calling the push()
method on an array and printing its value returns the new array length. Also, it added the items we passed to it to the end of the array.