Need an insight!

function A() {
 this.array = [] ;
  this.size = this.array.length;
};

let arr = new A();
arr.array.push("Element");
console.log(arr.size)
 //Output is 0

Can anyone tell me, what’s the logic behind this output?? Why won’t it update the length with the update of the array property in the object?

Can anyone tell me

3 Likes

This sets size as the value of array.length at the time this function is called.

1 Like

would adding

arr.array.push(“Element”);

not call the function again though???

1 Like

May I know, why it won’t update as I update the property when I’m referring to the object’s property?

No. That would not call the constructor again. That modifies only this.array.

1 Like

The length is a primative value, so you only get the value, not a reference to the value. To have multiple pieces of internal data change in response to one value changing, you’d need a setter. Or you could use a getter to update/retrieve the value you intend.

2 Likes

interesting. Thank you @JeremyLT for the explanation. and thanks @rajtanuchakravarty for the example

2 Likes

Thank you for the knowledge that you shared. I did some experiments and found out that what you said was true and it is valid.
It looks like your understanding of the concepts is quite strong.

Do you mind, if I ask you something? @JeremyLT

Go for it

1 Like

Are you one of the members of FCC? @JeremyLT

Everybody who participates in the community is member, and I’ve been around for a few years.

Haha…that doesn’t answer my question. But I think I got the answer. Anyways, it is nice knowing you. Keep helping us, who are just starting out. So, that we can do the same for others. @JeremyLT

That’s the idea! Learn and help as you go!

1 Like

Apart from that, I just started my DSA.
Got any advice for me?

That stuff is hard. Be patient with yourself and ask lots of questions if you get stuck. Learning how to get unstuck is a big part of becoming a programmer and sometimes that involves help.

1 Like

Appreciate the advice.
And will keep that in mind.
Thanks a bunch. :blush:

1 Like

Ohh man lol. I feel for you, I’m switching to C# because I like it more for I’d like to do but I’m stuck on my Udemy class on the ‘this’ keyword too.

Keep grinding mate. :muscle: