Let's say I have a factory function createFunction() with an integer variable and an array object.
function createFunction() {
let a = 5;
let arr = [];
function updateA (value) {
a = value;
}
function getA () {
return a;
}
function updateArr(value){
arr.push(value);
}
return {a, updateA, getA, arr, updateArr};
}
After updating a and arr, I try to access them.
const myFunction = createFunction();
myFunction.updateA(11);
console.log(myFunction.a); // prints 5
console.log(myFunction.getA()); // prints 11
myFunction.updateArr(33);
console.log(myFunction.arr); //prints [33]
I'm confused why the updated array can be accessed directly with myFunction.arr whereas the variable a cannot be accessed with myFunction.a. They are both exposed via the return in createFunction() and so I assume they have the same scope. Why can the updated value of a only be accessed using a getter method?