The Ninja The Ninja - 3 months ago 18
Javascript Question

Modifying an array outside a brace-initialized object

Behavioral question :

Why Ninja.getArrayFromInside() return an empty array ? (after Ninja.array modification)



let Ninja = (function() {

let array = [];

function getArrayFromInside() {
return array;
}

return {
array, getArrayFromInside
};

})();

Ninja.array = [1, 2];

console.log(Ninja.getArrayFromInside());





I think, it's about passing by Value or by Reference ...
(Why array is passed by value, and not by reference ?)

Same question here :



let Ninja = (function() {

let myObject = {};
myObject.array = [];

function getArrayFromInside() {
return myObject.array;
}

return {
array: myObject.array,
getArrayFromInside
};

})();

Ninja.array = [1, 2];

console.log(Ninja.getArrayFromInside());




qxz qxz
Answer

In the first example, there are two variables called array: the one declared let array = []; in the inner scope captured by the getArrayFromInside function, and the property Ninja.array. These are two different variables. The first you refer to by array; the second you could refer to by this.array inside the getArrayFromInside function.

You initialize them both to a reference to the same array object (which is initially empty). Then, you assign Ninja.array to reference a different object: the array [1, 2]. This does not modify the let array ... variable; since the function gets the value of the let array, it returns the original, still empty, array object.

Try changing Ninja.array = [1, 2]; to Ninja.array.push(1);Ninja.array.push(2);. You'll see that modifying the original array like this will result in the changes being reflected in the Ninja.getArrayFromInside() call.