FAQ: Arrays - The .push() Method


#1

This community-built FAQ covers the “The .push() Method” exercise from the lesson “Arrays”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise The .push() Method

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

The code:
chores.push(‘vacuum’, ‘dry dishes’);
console.log(chores);
works fine, returning the five items in the array.
However, trying to make it more concise by typing:
console.log(chores.push(‘vacuum’, ‘dry dishes’));
returns the number 5, which one would expect to be the result of chores.length. Am I missing something?


#3

The return value of the push method is the new length of the array. The statement is logging that return, not the chores array.

We can log a comma separated list of objects…

console.log(chores.push(‘vacuum’, ‘dry dishes’), chores);

#4

So the .push method simply increases the number of elements in the array to equal the total number, existing plus whatever I pass it in the parenthesis, and then places those new items into the corresponding spots?


#5

push() will append in the order the arguments are given, so the last item in the argument list will be the last item appended.

We can see the return as one of two things… The length of the new array, or the index of the next element, or what can be technically described as the first non-existing element of the array. This position is accessible.

    const a = [];
    console.log(a[0])    // undefined
    a[0] = 42;
    console.log(a);      // [42]

However, we cannot extend the list using a single index.

    a[1] = 6, 7, 13
    console.log(a);      // [42, 6]

As we can see, any past the first number is ignored. Hence the untility of the push() method.

    a.push(7, 13)
    console.log(a);      // [42, 6, 7, 13]