Tutorialspoint.dev

JavaScript | Array push()

arr.push() function is used to push one or more values into the array. This function changes the length of the array by the number of elements added to the array. The syntax of the function is as follows:

arr.push(element1[, ...[, elementN]])

Arguments This function contains as many numbers of arguments as the number of elements to be inserted into the array.

Return value This function returns the new length of the array after inserting the arguments into the array.

Examples for the above function are provided below:

Example 1:



var arr = [34, 234, 567, 4];
print(arr.push(23,45,56));
print(arr);

Output:

7
34,234,567,4,23,45,56

In this example the function push() adds the numbers to the end of the array.

Example 2:

var arr = [34, 234, 567, 4];
print(arr.push('jacob',true,23.45));
print(arr);

Output:

7
34,234,567,4,jacob,true,23.45

In this example the function push() adds the objects to the end of the array.

Codes for the above function are provided below:

Program 1:

// JavaScript to illustrate push() function
<script>
function func() {
  
    // Original array
    var arr = [34, 234, 567, 4];
  
    // Pushing the elements
    document.write(arr.push(23,45,56));
    document.write("<br>");
    document.write(arr);
}
func();
</script>

Output:

7
34,234,567,4,23,45,56

Program 2:

<script>
// JavaScript to illustrate push() function
function func() {
  
    var arr = [34, 234, 567, 4];
  
    document.write(arr.push('jacob',true,23.45));
    document.write("<br>");
    document.write(arr);
}
func();
</script>

Output:

7
34,234,567,4,jacob,true,23.45


This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter