Frequently, there is the call either add or remove elements while working with arrays. In this case, the push() and pop() functions come in handy in adding and removing elements from an array.
Addition of two new elements to the array’s end:
Array push() syntax
array.push(item1); array.push(item1,item2); array.push(item1,item2,...,itemX);
array.push(item1, item2, ..., itemX)
This method has as many parameters as there are elements to be added to the array. The parameters are:
item1- The thing(s) to include in the array item2 -There must be at least one item --- itemx
The Return Value
The return value is a number representing the array’s new length. Also, the push() method updates the length property of the array object on which the method is called and returns it. Actually, it returns the Number indicating the array’s new length.
The push() method can be combined with call() or apply() on array-like objects. The array uses the length attribute.push() method to determine where to insert the specified components. If the length cannot be translated to a number, the index of 0 is used. It also includes the possibility of length not existing, in which case length will be generated.
Example: Using the array push() method to append one element to an array
The example below appends the number 150 to the end of the numVars array:
let numVars = [110, 120, 130]; const numLength = numVars.push(150); console.log(numLength); console.log(numVars);
How does it work?
First, create a numVars array with three numbers:
let numVars = [110, 120, 130];
Second, using the push() method, append the number 150 to the end of the numVars array and assign the return value to the numLength variable:
const numLength = numVars.push(150);
Finally, print the numLength variable and the numVars array:
Example: Addition of 3 items to the array
This example illustrates how 3 items can be added at the same time.
const cars = ['Toyota', 'Nissan', 'Mazda']; const count = cars.push('Mercedes'); console.log(count); // expected output: 4 console.log(cars); // expected output: Array ["Toyota", "Nissan", "Mazda", "Mercedes"] cars.push('Ford', 'BMW', 'Honda'); console.log(cars);
Example: Using the array push() method to add several elements to the end of an array
The following code demonstrates how to add many entries to the end of an array using the push() method:
let numVars = [110, 120, 130]; const numLength = numVars.push(150, 179); console.log(numLength); console.log(numVars);
Example: Using push() to append array elements to another array
Assume you have two backend and frontend arrays:
let backend = ['PHP', 'Java', 'Python']; let frontend = ['Angular', 'Vue', 'ReactJS', 'AngularJS'];
And you want to append the frontend language elements to the backend language elements array. To accomplish this, create a for…of loop that iterates over the members of the frontend array. Subsequently, use the push() method to attach each element to the backend array, as seen below:
let backend = ['PHP', 'Java', 'Python']; let frontend = ['Angular', 'Vue', 'ReactJS', 'AngularJS']; for (const frLang of frontend) backend.push(frLang); console.log(backend);
Starting with ES6, you may use the spread operator (…) to distribute the items of the frontend array while also pushing them to the backend array, as shown below:
let backend = ['PHP', 'Java', 'Python']; let frontend = ['Angular', 'Vue', 'ReactJS', 'AngularJS']; backend.push(...frontend); console.log(backend);
As a mutating method example, is the push() method. It alters both the content and length of this. If you wish to keep the value of this but return a new array with additional elements, you can use arr.concat([item0, item1, /* … ,*/ itemN]) as an alternative. If you carefully analyze, you will realize that an extra array wraps the elements. In case the item being considered is an array itself, then instead of being pushed, it is spread as a single item. The latter is because of the behavior of the concat().
Array.prototype.push() is by default generic and you can use it with either apply() or call(). The push method engages the length property to decide where to start inserting the specified items. The index is 0 if the length attribute cannot be translated into a number by the push() method. It includes the scenario where length is hypothetical and length is subsequently created. Despite being native Array-like objects, strings are not appropriate for use with this function since they are immutable.
Consider the following:
How does it work?
First, create the codingLanguage object, which has three properties: 1, 2, and length, as well as one method: addVal().
To attach the newVar to the codingLanguage object, the addVal() method of the array object is invoked. Then, invoke the codingLanguage object’s addVal() method:
codingLanguage.addVal ('Java'); codingLanguage.addVal ('PHP');
Push() utilizes the codingLanguage object’s length property to determine where it appends the new element and increases the length property by one in each call. As a result, the codingLanguage object now includes two additional elements at indexes 2 and 3. After the calls, the length property is 4. Finally, print the codingLanguage object to the console:
To allow the addVal() method to take several newVar’s, alter it as follows:
How does this work?
Remove the newVar parameter from the addVal method first. Second, spread out the argument object’s elements and push them to the codingLanguage object.
Combining two arrays
const developers = ['White', 'Angel']; const newDevelopers = ['Joy', 'Green']; Array.prototype.push.apply(developers, newDevelopers); console.log(developers);
In case the second element, “newDevelopers,” is an array. It is advisable not to use apply() because there is a maximum number of arguments a single function can practically handle.
const developers = ['White', 'Angel']; developers.push('Joy', 'Green'); console.log(developers); // ['White', 'Angel', 'Joy', 'Green']
In this case, we have added two additional artists. Next, let’s examine the following code,
const developers = ['White', 'Angel']; const newDevelopers = ['Joy', 'Green']; artists.push(newDevelopers); console.log(developers);
As you can see here, the new third element being added is an array that is added as a whole. However, combining it as we did with the apply() is impossible. Alternatively, this example uses spread syntax to push all of the elements from a second array into the first one.
const compCompanies = ['Google', 'Facebook']; const additionalCompanies = ['Apple', 'IBM']; // Merging the latter array to the initial one compCompanies.push(...additionalCompanies); console.log(compCompanies);
Also, note that the method concat() is applicable in merging two given arrays.
How to use an object just as you would use an array
Since we know that push is intentionally generic from our previous sections, we can take advantage of that. In the example proceeding, we will illustrate how Array.prototype.push() can work like an object without complications.
const obj = length: 0, addItem(item) // obj.length is increases automatically // when a new item is added. .push.call(this, item); , ; // We can add some empty (though empty) objects for illustration purposes. obj.addItem (); obj.addItem (); obj.addItem (); console.log(obj.length); // → 3
The key takeaway is that despite the obj not being an array, the obj’s length is increased using the push method, similar to a real array.