Purpose of push function

What is the purpose of the push function? I know what it does and all, but when codding can’ you just type in the string into the array without the push the function? ik this question sounds dumb and I’ve been skeptical about posting it for days, but then, thank you for answering in advance:)

The Array.push() method let’s us add items to the end of an array.

We can build our array manually (hard coded), but then during the run session we can add to and take away from the array dynamically with either user inputs or generated data. Remember, during runtime we cannot edit the code.

const primes = [2, 3, 5, 7]
primes.push(11, 13, 17, 19)
console.log(primes)

[ 2, 3, 5, 7, 11, 13, 17, 19 ]


Above, we do hard code all the data, but for practical purposes we would write an algorithm to produce the next prime number, given the present one. Let’s try that…

const primes = [2, 3, 5, 7]
const isPrime = function (n) {
  if (n < 2) throw Error("ValueError!")
  for (let p of primes) {
    if (n % p === 0) return false
  }
  return true
}
const nextPrime = function () {
  const x = primes.slice(-1)[0]
  let y = x + 2
  while (! isPrime(y)) {
    y += 2
  }
  primes.push(y)
  return y
}
for (_ of Array(4)) console.log(nextPrime())
 11
 13
 17
 19
 > primes
=> [ 2, 3, 5, 7, 11, 13, 17, 19 ]   

You’ll learn how to write code like this or better, in time. Focus only on how we used .push() and ignore all the rest.

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