Javascript Spread operator confusing behavior

I don’t know how to type it on the title, and if by any chance it duplicated please tell me about it since I’m confused as what keyword I must search for this problem.

basically I have a problem or got confused with javascript or typescript spread operator behavior. I stumbled this problem just today when working with drag and drop function, but I will give you a simple example for this issue. let say I have a simple array like this

test = [
    {
        name: 'A',
        id: 1
    },
    {
        name: 'B',
        id: 1
    },
    {
        name: 'C',
        id: 3
    },
    {
        name: 'D',
        id: 4
    },
    {
        name: 'E',
        id: 5
    },
]

let say I want to make a shallow copy for the array, at first I’m doing it like this because it reflex for me and I not realized it until I do a recheck for my code.

my first code for it:

const tempArray = { ...test }
console.log('cek data : ', tempArray) // will result on array

if you see on my code it using {} or Object as the capsulating method right? but I don’t realize it because it works showing an array for me, but when I do recheck and change it into this

const tempArray = [...test]
console.log('cek data : ', tempArray) // will result on array since it using literal array

and it still correct and showing an array of object, can you tell me what we called this behavior so I can search it later and explain why this is showing the same correct result? is it because it make it object into array numeric but not showing it on console or any other explanation for this?

EDIT 1:

here is my result

ah I see thanks for pointing out, when I check it again yeah it show a different result, I missed it because it looks the same but as you can see on the image the object one make it looks like an array but in fact it makes an object by adding number as its key

>Solution :

It looks to me like you have misread the first output.

Running this code results in an object with the index of the input array as a keys, and the values of the array as values.

Output when running this in the Chrome console

Leave a Reply