Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Can't Call Push On Array Inside Another Function [duplicate]

I have a really simple JavaScript question...

I have a function, Pets, that contains three variables: an integer, a string, and an array defined as follows:

function Pets() {
    var index;
    var name;
    var animals = ["cat", "dog"];
}

In another function just below this one I declare a variable of type Pets and push "mouse" onto the animals array. I then do a console log to see the values.

function Test() {
    ...
    var pets = new Pets();
    pets.index = 1;
    pets.name = "My Pets";
    pets.animals.push("mouse");
    console.log(pets);
}

For whatever reason I didn't see any output from the console.

I then added some more console logging before and after calling animals.push:

    var pets = new Pets();
    pets.index = 1;
    pets.name = "My Pets";
    console.log("BEFORE PUSH");
    console.log(pets);
    pets.animals.push("mouse");
    console.log("AFTER PUSH");

And here is my output:

BEFORE PUSH
Pets {index: 1, name: "My Pets"} 

Note that I only see the first console log and not the second (after the push) which I presume indicates a problem with calling push on animals.

Also note that the console output shows that Pets has a property called index and a property called name but nowhere does it indicate that there is also a property called animals which is my array.

I tried changing the array declaration to:

var animals = new Array();

but that didn't seem to help either.

Is there something special that I have to do to initialize the animals array before I can push elements on to it? More generally, why doesn't the property animals even show up as part of the Pets class?

Thank you,

Jan

like image 797
Jan Tacci Avatar asked Dec 30 '25 17:12

Jan Tacci


1 Answers

You are declaring your variables in a way that will not make them visible outside the the Pets constructor function

This is why you do not see the second console because the line

pets.animals.push("mouse");

will throw the error TypeError: Cannot read property 'push' of undefined (or similar depending on browser). This will cause the rest of the script to stop executing.

The only reason you see index and name in the first console log is because you are creating them on the object after creating your Pets object. You need declare them using this operator or by setting them up on the prototype

function Pets() {
    this.index = null;
    this.name = null;
    this.animals = ["cat", "dog"];
}
like image 184
Patrick Evans Avatar answered Jan 02 '26 05:01

Patrick Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!