Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why empty slots are being replaced with undefined while cloning array using spread syntax?

I’m creating a clone array from an array that contain some empty slots. But after cloning it is being replaced with undefined. If the source array contain some empty slots then clone array should also contain same number and at exact same position empty slots. I don’t get the reason. I’m using spread syntax to clone array as:

const arr = [1, "", , null, undefined, false, , 0];
console.log('arr => ', arr);

const clone = [...arr];
console.log('clone => ', clone)

Output is as below in chrome console

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using spread syntax will invoke the object’s iterator if it has one. The array iterator will:

a. Let index be 0.
b. Repeat
  Let len be ? LengthOfArrayLike(array).
  iii. If index ≥ len, return NormalCompletion(undefined).
  (...)
    1. Let elementKey be ! ToString(𝔽(index)).
    2. Let elementValue be ? Get(array, elementKey).
    (yield elementValue)
  vi. Set index to index + 1.

And the length of a sparse array is still the index of the last element plus one:

const arr = [];
arr[5] = 'a';
console.log(arr.length);

So, even with sparse arrays, spreading them will result in the new array containing values of:

arr[0]
arr[1]
arr[2]
// ...
arr[arr.length - 1]

even when the original array has empty slots in between 0 and arr.length - 1.

If you want empty slots, spreading will only work if you delete the undesirable indices afterwards – or iterate over the array manually, only assigning indices you need.

const arr = [1, "", , null, undefined, false, , 0];
console.log('arr => ', arr);

const clone = [];
for (let i = 0; i < arr.length; i++) {
  if (arr.hasOwnProperty(i)) {
    clone[i] = arr[i];
  }
}
console.log('clone => ', clone)

But you could also consider restructuring your code to avoid sparse arrays entirely – they’re not very intuitive.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading