console.log(myArray.push )

Tell us what’s happening:
Why this : console.log(myArray.push([“dog”, 3])); gives me the number 4 as a result ?
I thought it should give me the hole new myArray object after “pushing” a new array in it

Your code so far

// Setup
var myArray = [["John", 23], ["cat", 2]];
myArray.push(["dog", 3]);
// Only change code below this line
console.log(myArray.push(["dog", 3]))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.74.

Challenge: Manipulate Arrays With push()

Link to the challenge:

it’s how push works

The push() method adds one or more elements to the end of an array and returns the new length of the array.

The length should be 3 then not 4 ?

there is an other push method two lines above your console.log that add a third element to the array, the logged push add a fourth elemebt

1 Like

Now I see, I added an other one without paying attention to it . Thanks :slight_smile:

function push (array, ...itemsToPush) {
    //array is the array you wish to mutate
    //itemsToPush would be the arguments to append on the end of array

    for (let i = 0; i < itemsToPush.length; i++) {
        //this appends the items to the array without pushing
        array[array.length] = itemsToPush[i];
    //push returns the length of the mutated array
    return array.length;

This is kind of how push works if you were to write it out

1 Like

This works because an array is indexed by zero, but it actual length is defined by how we would normally count so if I have an array of [1,2,3] the length property would be equal to 3 but the last elements index is only 2 so if I were to access the array such as array[array.length] it would give me undefined as there is nothing there so I can effectively append thing to the end of an array by saying array[array.length] = item and each iteration the length will have increased so I will always be appending to the end.

1 Like

Many thanks, it is beautiful how you understand it. But is there any documentation showing how functions/properties are actually written ?

ECMASCRIPT say how things in JavaScript should work and then its up to the browser to implement them. Google and Firefox may have different approaches to the same task although tehy generally try to keep it simillar. MDN is a great resource and is also owned by the people who make Firefox.

1 Like

Yeah, this website is the most comprehensive documentation:

1 Like