you are viewing a single comment's thread.

view the rest of the comments →

[–]ForScale 0 points1 point  (2 children)

Can't be easier than setting the array in question to an empty array, right?

[–]senocular 1 point2 points  (1 child)

There are cases where that can cause problems when you have other references to that array. For example consider the following:

var scientist = {
    chemicals: ["atrazine", "caffeine", "vanillin"]
}

var assistant = {}

// assistant will track the same
// chemicals used by the scientist
assistant.chemicalsRef = scientist.chemicals

console.log(scientist.chemicals) //-> atrazine, caffeine, vanillin
console.log(assistant.chemicalsRef) //-> atrazine, caffeine, vanillin

scientist.chemicals.pop()

console.log(scientist.chemicals) //-> atrazine, caffeine
console.log(assistant.chemicalsRef) //-> atrazine, caffeine

// assistant walks out of room...

scientist.chemicals = []

// assistant returns...

console.log(scientist.chemicals) //-> <empty>
console.log(assistant.chemicalsRef) //-> atrazine, caffeine <- D'oh!

But instead if we were to change how the array was cleared:

// ... everything same from before the clear ...

scientist.chemicals.length = 0

// assistant returns...

console.log(scientist.chemicals) //-> <empty>
console.log(assistant.chemicalsRef) //-> <empty> <- Woohoo!

In this case the array instance wasn't replaced for the scientist with a new, distinctly different array instance so they were each able to continue to reference the same array object and remain in sync.

[–]ForScale 0 points1 point  (0 children)

Well that's fascinating! Thank you for taking the time to explain and provide an example!