Push JavaScript

In this lesson we will see how to insert data into a JavaScript array push method, useful to insert element in array.

The syntax of this method is as follows: array.push(element).

Where array is the name of our array we want to populate. Element represents what we want to insert in the array.

You can also insert more elements and in this case, therefore, the syntax is as follows:

arrayname.push(element1, element2,…, elementon).

The element or elements will be inserted at the end of the array, that is, from the right.

Let’s now make some simple examples to better understand how this method works.

JavaScript array push – first example

Create an array that can contain everything related to eg school material. Then we ask the user for the name of something he wants to insert into this array and we add it to the initial array.

So suppose we have an initial array that contains 3 elements, such as this:

var schoolObjects = [‘rubber’, ‘notebook’, ‘pencil’];

Then we ask the user to insert an element and storing it in a User object variable. So let’s add this element into our array.
Here, then, is the complete code of the exercise that uses the push instruction in JavaScript:



var schoolObjects = ['eraser', 'notebook', 'pencil'];
var objectNew = prompt('Insert a school object');
schoolObjects.push(new object);
console.log(schoolObjects);

We simply display the final contents of our array in the browser console.

JavaScript array push – second example

Populate an empty array with 10 integers required by the user.

So we will first need to define an empty array and then, with a for loop, we need to ask the user for the numbers and populate the array in this way.

Here is the example code for solving the algorithm:


var numbers = [];
var number;
for (let i = 0; i < 10; i ++) {
  number = parseInt(prompt('Enter a number'));
  numbers.push(number);
}
console.log(numbers);

For convenience, we always display the final array in the console of our browser.

Conclusion

In this lesson we have dealt with simple examples on JavaScript array push method, in the next lessons we will further explore this instruction.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *