0 0
WP Ad Inserter plugin
Read Time:8 Minute, 29 Second

Table of Contents

Arrays are essential for completing programming tasks in any programming language. In fact, arrays refer to list objects with methods for performing mutation operations. The length of a JavaScript array and the types of its items are not fixed. Arrays in JavaScript are used to hold several values in a single variable. An array data structure can store multiple values under a single name, which can be accessed by referring to the index number. In javascript, arrays store the same data kinds as texts, integers, arrays, and even functions.

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.

This post will explain the push() functions in JavaScript and provide some examples to help you grasp them better.

Javascript array addition

To add elements to a JavaScript array, append as many elements as possible, such as integers, strings, arrays, objects, an array of strings, an array of integers, and an array of arrays. To include a new item in an array, we use the push() method. Push() adds new elements to an array’s end.

const programmingLanguages = ["JavaScript", "PHP", "Python", "Java"];
programmingLanguages.push("Kotlin");
console.log(programmingLanguages)

Addition of two new elements to the array’s end:

SUGGESTED READ

const programmingLanguages = ["JavaScript", "PHP", "Python", "Java"];
programmingLanguages.push("Kotlin","Ruby" );

Array push() syntax

array.push(item1);
array.push(item1,item2);
array.push(item1,item2,...,itemX);

or

array.push(item1, item2, ..., itemX)

Parameters

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:

SUGGESTED READ

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:

console.log(numLength);
console.log(numVars);

Example: Addition of 3 items to the array

This example illustrates how 3 items can be added at the same time.

const programmingLanguages = ["JavaScript", "PHP", "Python", "Java"];
programmingLanguages.push("Kotlin","Ruby","C++" );

or

SUGGESTED READ

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);

How the JavaScript Array push() method is used with array-like objects

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().

SUGGESTED READ

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 afterward created. Despite being native Array-like objects, strings are not appropriate for use with this function since they are immutable.

Consider the following:

let codingLanguage = { 0: 'Python', 1: 'JavaScript', length: 2, addVal(newVar) { [].push.call(this, newVar); },
};
codingLanguage.addVal ('Java');
codingLanguage.addVal ('PHP'); console.log(codingLanguage);

How does it work?

First, create the codingLanguage object, which has three properties: 1, 2, and length, as well as one method: addVal().

let codingLanguage = { 0: 'Python', 1: 'JavaScript', length: 2, addVal(newVar) { [].push.call(this, newVar); },
};

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:

SUGGESTED READ

console.log(codingLanguage);

To allow the addVal() method to take several newVar’s, alter it as follows:

let codingLanguage = { 0: 'Python', 1: 'JavaScript', length: 2, addVal(newVar) { [].push.call(this, ...arguments); },
};
codingLanguage.addVal ('Java', 'PHP'); console.log(codingLanguage);

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

In JavaScript, utilize the array.push() function to merge arrays. To combine arrays, use the array.push() method. Consider the following example of merging 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 count of arguments a single function can handle practically.

The apply() method adds the second array(“newDevelopers”) into the first array(“developers”), then returns the initial array, which is developers in this case. Other alternatives to adding one array into another include using the array’s concat() function and the JavaScript concat().

SUGGESTED READ

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 generic intentionally 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.

It’s worth noting that we don’t use an array to hold a collection of things. Instead, we store the collection on the object itself and use Array.prototype.push to fool the function into believing we’re dealing with an array—and it just works, owing to JavaScript’s ability to set the execution environment in any way we want.

SUGGESTED READ

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.

Conclusion

In this lesson, you’ve learned how to add one or more elements to the end of an array using the JavaScript Array push() method. The push() method is responsible for changing the length of an Array or collection and can append a number, text, object, Array, or any value to it. In addition, we have also looked at several different examples to help drive the point home.

Source: https://www.codeunderscored.com/array-push-method-in-javascript/

Beginner’s guide to Anaconda Python Previous post Beginner’s guide to Anaconda Python
Deque Python with examples Next post Deque Python with examples

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.