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();