Skimrande
Skimrande

Reputation: 831

Any downsides to copying frozen array in JavaScript?

In JavaScript, arrays are objects and objects can be frozen, so I guess this can be done?

const frozenArr = Object.freeze([1, 2, 3, 4, 5])

thus

//frozenArr.push(6) //does not work, "Cannot add property 5, object is not extensible..."

However if I create a new array from the frozen one

const anotherArr = Array.from(frozenArr)

then

anotherArr.push(6) // works

My questions to you are, are there any downsides to copying a frozen array? Which is its prototype, and did it inherit any unwanted properties from it? Thanks in advance!

Upvotes: 0

Views: 645

Answers (1)

Dhananjai Pai
Dhananjai Pai

Reputation: 6005

Onlydownside? may be that you are cloning the original object/array and thus doubling the memory! Otherwise, you can definitely copy the object, but it is not related to the first object in anyway. Any updates will not affect the original array/object.

Upvotes: 3

Related Questions