One of my app functions is responsible for storing data. It allows users to add new items and returns the length of the data array.
I've observed a strange behavior where returning the data itself in a function includes the pushed items, but returning data.length
or using a filter does not. Surprisingly, when I request the data length outside of the app function scope, it does show the added items.
In this particular case, getfn
, app.data.length
, and app.data.filter
properly reflect the added items, while getcntfn
and filterinitialfn
do not. What could be causing this unexpected outcome?
var app = (function () {
var data = ["initial"];
function add(x) { data.push(x) }
function getfn() { return data };
function getcntfn() { return data.length };
function filterinitialfn(filter) { return data.filter(x => x == filter) }
return {
add: function (x) { add(x) },
data:data,
getfn: getfn(),
getcntfn: getcntfn(),
filterinitialfn: function(filter) {filterinitialfn(filter)}
}
}());
app.add("added")
console.log("app.getfn", app.getfn) //["initial", "added"]
console.log("app.getcntfn", app.getcntfn) //1 ???
console.log("app.data.length", app.data.length) //2
console.log("app.filterinitialfn", app.filterinitialfn("added")) //[] ???
console.log("app.filterinitial=>", app.data.filter(x => x == "added")) //["added"]