Basic JavaScript - Manipulate Arrays With push Method

Tell us what’s happening:
Describe your issue in detail here.

I don’t need help with this exercise but I’m just wondering when would you ever actually need to use the .push function? Wouldn’t it just be simpler to write out the value instead of actually typing out the .push function?

Your code so far

// Setup
const myArray = [["John", 23], ["cat", 2]];

// Only change code below this line
myArray.push(["dog", 3])

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15

Challenge: Basic JavaScript - Manipulate Arrays With push Method

Link to the challenge:

This challenge is just showing you the push method with a simple example. In this specific instance, there isn’t really a good reason to use it other than to show how it works.

It will make more sense as you progress through the curriculum.


But the entire point of code is to do things dynamically at runtime based on some logic of the program. Often, you simply don’t even know the data ahead of time and can not add it by hand. Or the data is part of some input or computed by other code logic.

const numbers = [];

numbers.push(Math.floor(Math.random() * 100));
console.log(numbers); // [random value]
numbers.push(Math.floor(Math.random() * 100));
console.log(numbers); // [random value, random value]

This is one simple example of the usage of the push() method to get random Bingo numbers. This is not possible to get by adding numbers manually into the array:

// Setup
const myArray = [];

// Only change code below this line
function bingoSeven(min, max) {
for (let i = 1; i <= 7; i++) {
myArray.push(Math.floor(Math.random() * (max - min + 1)) + min);
  }
  return myArray;
}

console.log(bingoSeven(1, 32));

The following is one of the random combinations obtained from the code above:
image

Every time you call the function, you get a new combination of seven numbers from 1 to 32.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.