Array/Object via reference alternative as non-reference

I know, this is normal object behavior.
The intent of the proposal is to make working with array/object more... convenient.

Code example:

let test1 = { arr: [] };
let test2 = {};
test2.arr = test1.arr; // reference bound to secondary location
test1.arr.push(1);
console.log(test2.arr[0]); // 1
test1.arr = []; // you as a developer actually want to clear the array, but you are rebinding a reference to `test1` which is no longer bound to `test2`

To prevent this behavior, you should always write your own array clearing method using this code:

for (let i = 0; i < test1.arr.length, i++) {
test1.arr.splice(i, 1);
i--;
}

It's not just this test example that's the problem, but when people reference your deep configs somewhere in their own configs - all the getters/setters/refs lose their connection to the original location.

The object way is to keep references as long as possible, because they are "objects".

But javascript syntactic sugar usually suggests doing something like this:

let newArray = [].concat(oldArray);

or

let newArray = oldArray.filter(myFuncHere);

or

let newObject = { ...oldObject, newProp1: newValue1 };

All of these methods involve losing the reference to the original array, and this is probably the MOST COMMON javascript pitfall in general (second pitfall is to call setTimeout(this.method, 1000) instead of setTimeout(this.method.bind(this), 1000))

It would be great to optimize sugar to work like this - short initializers (meaning let a = [] or let a = {}) and all - binding new data to properties never recreates native objects (like PHP language does).

If you want to work with properties using object way, you will have to create new Object or new Array (without sugar), because you directly know what you are doing.

I know this isn't the main point of your post but just wanted to mention a tip. The above is an inefficient way to clear an array. It can be done in a single step: arr.length = 0.

1 Like

Thanks, I didn't know that. Actually I understand that splice is not the best way, because the array has to be rebuilt internally (with resetting all keys, many interpreter steps), but about .length = 0 - thanks again.

Maybe there is a possibility to clear empty array elements after some delete arr[i] calls? I mean - rebuild array indices after deletion is done?

up

delete should be avoided on arrays, it creates a "holey array", with missing properties. Most engines will deoptimize index access if an array becomes holey.