0

I created a variable to hold the total number of elements in the array using myArray.length. Then I use myArray.push() to add an element to the array.

the original array has 3 elements, so the .length returns 3, which is correct. But when I added an element to the array and I console.log(the Var which contains the .length property ), it just does not work. the Var still shows 3 for the array. However, if I use xxx.length, the number is correct now.

var collection = function() {
  //two properties
  var items = ["basketball", "football", "soccer"];
  var number = items.length;

  console.log(items);
  console.log("the number of the items in the array is " + number);

  // two private methods
  var addItem = function(newItem) {
    items.push(newItem);
    console.log(items);
  };

  var showNumber = function() {
    console.log(number) //this one returns 3, which is not correct
    console.log("the number of the items in the array is " + items.length);
  }; // this one returns 4, which is correct



  // two public methods
  return {
    getItem: addItem,
    getNumber: showNumber,
  };
}();


collection.getItem("pingpong");
collection.getNumber();
ikhvjs
  • 5,316
  • 2
  • 13
  • 36
Qiyuan Liu
  • 27
  • 3
  • `number` contains the value that `items.length` had. It is not a reference to `items.length`. Try updating `number` inside `addItem`? – evolutionxbox Jan 19 '22 at 15:31
  • you need to update `number` value in the `addItem` method. – Saeed Shamloo Jan 19 '22 at 15:32
  • Sounds like a good reason to _not_ introduce such an extra property. You have access to the count via `items.length` already, so _why_ invent your own property just to "mirror" that value? – CBroe Jan 19 '22 at 15:34
  • As others have already mentioned, the value in `number` is never updated after you initially set it. It doesn't get updated just because you add something to the array. Just return `items.length` from your `getNumber()` function and it will always be accurate. – tehbeardedone Jan 19 '22 at 15:34

0 Answers0