FAQ: Arrays - The .push() Method

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!

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?

1 Like

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

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?

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 utility of the push() method.

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

Edit: 9/14/2021 - spelling correction (mtf)

6 Likes

what is the difference between ‘let’ and ‘const’ variables which are representing arrays, since we can change elements inside an array declared by const?

We can mutate the elements of an array no matter how it is declared. The only constant is that it is a data structure we don’t want replaced with any other value.

let array = []
array = "another type of iterable"    // permitted

const array = []
array = "some other value"
> Uncaught TypeError: Assignment to constant variable.
1 Like

Hey,

I’m curious about the following way of updating a list.

let groceryList = ['bread', 'tomatoes', 'milk'];

groceryList = groceryList.push('butter');

console.log(groceryList);
console.log(groceryList.length);

The first prints ‘4’, the second prints ‘undefined’. I checked with a typeof keyword, and it returns a ‘number’ type:

console.log(typeof groceryList);

Note, I ran a similar code on Python (I appreciate they are different languages):

grocery_list = ['bread', 'tomatoes', 'milk']

grocery_list = grocery_list.append('butter')

print(grocery_list)

print(type(grocery_list))

It seems that here, the list type is transformed to a NoneType class. I’m quite curious for both languages as to what happens in the background, especially how a list is transformed to what is respectively an number and a NoneType in JS and Python. Any ideas?

Thanks,
Twan

The return value of push() is the new length of the array, that’s why it prints 4.

You have effectively replaced the array with a number by assigning back to that variable.

groceryList.push('butter')

is a complete statement. No need to assign, but if you wish to assign, then use a different variable

newLength = groceryList.push('cheese')

console.log(groceryList)
// ['bread', 'tomatoes', 'milk', 'butter', 'cheese'];
console.log(newLength)
// 5
7 Likes

out of sheer curiosity, why are the items in the array logged to the console vertically? the other examples just list them in a wrap text format.

2 Likes

It is common to see lists rendered vertically in the console. Nothing to read into that. Note that there are still square brackets and the values are comma separated.

2 Likes

Hi I hope is everyone doing good, I just like to ask, the difference between the method and functions, as per discussed in this section of the array, the .push() is defined as a method.

One method, .push() allows us to add items to the end of an array.

But also we can call the .push() method as a function because .push() is a function itself, I just like to clarify what’s the difference between these terms? or are they the same?

Then we call it like a function. That’s because .push() is a function and one that JavaScript allows us to use right on an array.

Thank you so much.

2 Likes

A method is a function, only it cannot be accessed globally the way functions can. It can only be accessed by instances of the class it belongs to.

When we look at the .push() and .pop() methods we see that they are methods of the Array class, or more particularly, methods in the prototype of the Array constructor.

Array.prototype.push()
Array.prototype.pop()

If we attempt to call the methods on a ‘string’ object, it will throw a TypeError since the String class does not have a push or pop method.

So when you see the word method, expect it to be a property of the instance it is called on, as indicated by the dot notation.

4 Likes

Thanks for the clarification, that made it clear my confusions on both terms. Thanks you so much.

1 Like

so using the .push() method we do not assign to constant variable? It is considered the same as if we just changed some of the elements but the array remained the same, even though we added

chores = [‘wash dishes’, ‘do laundry’, ‘take out trash’, ‘do sports’, ‘sleep’]; // this is assignment and is not allowed
chores.push(‘do sports’, ‘sleep’); // this would have the same effect but it is not considered as assignment (creating new array) somehow

But it is. The values were assigned to new elements at the end of the array in the same order they are given to the .push() method.

1 Like

Why we call .push() as a destructive array method. but from the concept, push adds elements. a bit confusing

Can you please show us where you read this?

@haxorgzr perhaps you mean mutable?

Which immediately came to mind if we interpret mutation as akin to destruction of the original state. The member has yet to respond.